package models.contacts;

import com.google.gson.annotations.Expose;
import models.Company;
import models.Task;
import models.projects.Project;
import play.Logger;
import play.db.jpa.JPA;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by dom on 4/12/2018.
 */
@Entity
public class Customer extends Contact {

    @Embedded
    public FinancialInfo financialInfo;

    @OneToMany(mappedBy = "customer")
    public List<Person> employees = new ArrayList<>(); //employees of the Customer some of them may be Associates

    @OneToMany(mappedBy = "customer")
    public List<Project> projects = new ArrayList<>();


    public Customer() {

    }

    public Customer(String afm, String doy, String fullName) {
        super();
        this.financialInfo = new FinancialInfo(afm, doy, fullName);
    }

    public Integer numberOfTasks() {

        int tasks = 0;
        List<Task> tmp;
        for (Person p : this.employees) {
            if (p.taskSet.size() > 0) {

                //first lets take the todos and not the deliverables
                tmp = p.taskSet.stream().filter(t -> t.getClass().getSimpleName().equals("Task")).collect(Collectors.toList());
                if (tmp.stream().filter(t -> t.status.equals("0")).count() > 0) {
                    tasks += p.taskSet.size();
                }
            }
        }
        for (Project proj : this.projects) {
            Logger.info("proj tasks " +proj.tasks.size());
            if (proj.tasks.size() > 0) {
                tmp = proj.tasks.stream().filter(t -> t.getClass().getSimpleName().equals("Task")).collect(Collectors.toList());
                if (tmp.stream().filter(t -> t.status.equals("0")).count() > 0) {
                    tasks += tmp.size();
                }
            }
        }
        return tasks;
    }

    public String getTotalRevenue() {
        BigDecimal sum = BigDecimal.ZERO;
        for (Project proj : this.projects) {
            sum = sum.add(proj.financialInfo.cost);
        }

        return sum.toString();
    }

    public String getProjectsStatus() {
        String result = "";

        if (this.projects.stream().anyMatch(p -> p.status.equals("3"))) {
            result = "3";
        }
        if (this.projects.stream().anyMatch(p -> p.status.equals("1"))) {
            result = "1";
        }
        if (this.projects.stream().anyMatch(p -> p.status.equals("2"))) {
            result = "2";
        }


        return result;
    }
}
