package models;

import com.google.gson.annotations.Expose;
import models.contacts.Person;
import models.projects.Deliverable;
import models.projects.Project;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import play.Logger;
import play.db.jpa.JPA;
import play.db.jpa.Model;
import play.mvc.Router;

import javax.persistence.*;
import java.util.*;

/**
 * Created by dom on 15/12/2018.
 */
@Entity
public class Task extends Model implements Event {
    public static final String DD_MM_YYYY = "dd-MM-yyyy";

    public Integer numbering;

    @Searchable
    public String description;

    public String status; //0:PENDING, 1:DONE

    @ManyToOne
    public Company company;

    @ManyToOne
    public Project project;

    @ManyToMany
    public Set<AppUser> userSet = new TreeSet<>();

    @ManyToOne
    public AppUser uploader;

    @Column
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    public DateTime createdDate;

    @Column
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    public DateTime startDate;

    @Column
    @Expose
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    public DateTime endDate; //when the task was marked as completed or if a deliverable then the date its due

    @ManyToOne
    public AppUser endedBy; //the user that marked the task as completed

    @Override
    public String toString() {
        return description;
    }

    public Task() {

    }

    public boolean hasAssociates() {
        if (!this.userSet.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isAssignedTo(Long userId) {
        AppUser user = AppUser.findById(userId);
        if (this.userSet.contains(user)) {
            return true;
        } else {
            return false;
        }

    }

    public Integer getMaxNumbering() {
        String sql = "SELECT max(numbering) FROM Task t where t.company =:comp";
        Query query = JPA.em().createQuery(sql);
        query.setParameter("comp", company);
        Integer maxnumber = (Integer) query.getSingleResult();
        if (maxnumber == null) {
            maxnumber = 0;
        }
        return maxnumber;
    }

    public boolean hasReminders() {
        String sql = "SELECT COUNT(r) FROM Reminder r where r.task =:tsk";
        Query query = JPA.em().createQuery(sql);
        query.setParameter("tsk", this);
        long ldoneTasks = (long) query.getSingleResult();
        if (ldoneTasks == 0) {
            return false;
        } else {
            return true;
        }
    }

    public String getCreateDateString() {
        if (this.createdDate == null) {
            return "";
        }
        DateTimeFormatter fmt = DateTimeFormat.forPattern(DD_MM_YYYY);
        return fmt.print(createdDate);
    }

    public String getEndDateString() {
        if (this.endDate == null) {
            return "";
        }
        DateTimeFormatter fmt = DateTimeFormat.forPattern(DD_MM_YYYY);
        return fmt.print(endDate);
    }



    @Override
    public DateTime getStartDate() {
        return createdDate;
    }

    @Override
    public String getTitle() {
        return description;
    }

    @Override
    public String getCalendarContent() {
        Map map = new HashMap<String, Object>();
        Map map2 = new HashMap<String, Object>();

       // map2.put("id", this.uploader.id);
      //  String url2 = ""; //  Router.reverse("Contacts.addAssociate", map).url;

        if(this.project != null) {
            map.put("id", this.project.id);
            String url = Router.reverse("Projects.addProject", map).url;
            return "Task concerning project : <a class='user yellow'  href='" + url + "'>" + this.project.name + "</a><br/>&emsp;" + this.description + "<br/><br/>Noted by <a class='user yellow'  href='#'>" + this.getUploadedBy() + "</a>";
        }


        return this.description + "<br/><br/>Noted by <a class='user yellow'  href='#'>" + this.getUploadedBy() + "</a>";
    }



    @Override
    public String getUrl() {
        return "";
    }

    @Override
    public String getUploadedBy() {
        return this.uploader.userName;
    }

    @Override
    public JSONEvent getEvent() {
        JSONEvent event = new JSONEvent(getStartDate().toDate(), "Task: " + getTitle(), getCalendarContent(), "#428bca", this.getUrl(), this.getUploadedBy(), this.getClass());
        return event;
    }
}
