package performa.intercom.utils;

import static java.lang.System.currentTimeMillis;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.rdbms.filters.EqualsFilter;
import oneit.security.SecUser;
import oneit.utils.filter.CollectionFilter;
import oneit.utils.filter.Filter;
import performa.intercom.resources.Company;
import performa.intercom.resources.CustomAttribute;
import performa.intercom.resources.Event;
import performa.intercom.resources.Intercom;
import performa.intercom.resources.User;
import performa.orm.Job;
import performa.orm.types.JobStatus;
import performa.utils.Utils;


public class IntercomUtils 
{
    static
    {
        Intercom.setToken(Utils.INTERCOM_TOKEN);
        Intercom.setAppID(Utils.INTERCOM_APP_ID);
    }
    
    
    public static User createIntercomUser(SecUser secUser, String role, Company company, String phone)
    {
        try
        {
            User    user = new User();
                                
            user.setUserId(secUser.getIdentification());
            user.setEmail(secUser.getEmail());
            user.setName(secUser.getName());
            user.setPhone(phone);
            user.addCustomAttribute(CustomAttribute.newStringAttribute("role", role));    
            
            if(company != null)
            {
                user.addCompany(company);
            }
            
            return User.create(user);
        }
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while creating a user in intercom");
            
            return null;
        }
    }
    
    
    public static User findUserByID(SecUser secUser)
    {
        try
        { 
            Map<String, String> map = new HashMap<>();

            map.put("user_id", secUser.getIdentification());

            return User.find(map);
        }
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while fetching a user by id from intercom");
            
            return null;
        }
    }
    
    
    public static User updateIntercomUser(SecUser secUser, String phone)
    {
        try
        {        
            User user   =   findUserByID(secUser);
            
            if(user != null)
            {
                user.setEmail(secUser.getEmail());
                user.setName(secUser.getName());
                user.setPhone(phone);
                User.update(user);
            }
            
            return user;
        }
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while updating a user in intercom");
            return null;
        }
    }
    
    
    public static Company createIntercomCompany(performa.orm.Company company, ObjectTransaction transaction)
    {
        try
        {        
            Company intercomCompany =   new Company();
                                                
            intercomCompany.setName(company.getCompanyName());
            intercomCompany.setCompanyID(company.getID().toString());
            
            Job[]       jobs        =   Job.searchCompany(transaction, company);
            Filter      filter      =   Job.SearchByAll().andJobStatus(new EqualsFilter<>(JobStatus.DRAFT));
            Collection  draftJobs   =   CollectionFilter.filter(Arrays.asList(jobs), filter);
            
            intercomCompany.addCustomAttribute(CustomAttribute.newIntegerAttribute("job-count",  jobs != null ? jobs.length : 0));    
            intercomCompany.addCustomAttribute(CustomAttribute.newIntegerAttribute("draft-job-count",  draftJobs.size()));    

            return Company.create(intercomCompany);
        }
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while creating a company in intercom");
            
            return null;
        }
    }
    
    
    public static Company findCompanyByID(performa.orm.Company company)
    {
        try
        { 
            Map<String, String> map = new HashMap<>();

            map.put("company_id", company.getID().toString());

            return Company.find(map);
        }
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while fetching a company by id from intercom");
            
            return null;
        }
    }
    
    
    public static void updateCompany(performa.orm.Company company, ObjectTransaction transaction)
    {
        try
        { 
            Company intercomCompany =   findCompanyByID(company);
        
            if(intercomCompany == null)
            {
                createIntercomCompany(company, transaction);
            }
            else
            {
                intercomCompany.setName(company.getCompanyName());
                
                Job[]       jobs        =   Job.searchCompany(transaction, company);
                Filter      filter      =   Job.SearchByAll().andJobStatus(new EqualsFilter<>(JobStatus.DRAFT));
                Collection  draftJobs   =   CollectionFilter.filter(Arrays.asList(jobs), filter);
                
                intercomCompany.addCustomAttribute(CustomAttribute.newIntegerAttribute("job-count",  jobs != null ? jobs.length : 0));    
                intercomCompany.addCustomAttribute(CustomAttribute.newIntegerAttribute("draft-job-count",  draftJobs.size())); 
            
                Company.update(intercomCompany);
            }
        }   
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while updating company in intercom");
            
        }
    }
    
    
    public static Company findOrCreateCompany(performa.orm.Company company, ObjectTransaction transaction)
    {
        Company intercomCompany =   findCompanyByID(company);

        if(intercomCompany == null)
        {
            intercomCompany =   createIntercomCompany(company, transaction);
        }

        return intercomCompany;
    }
    
    
//    public static void createAccessedJobEvent(Job job, User user)
//    {
//        try
//        {
//            Map<String, CustomAttribute> customAttributes = user.getCustomAttributes();
//            customAttributes.get("shortlisted-count");
//            Event   event   =   new Event();
//
//            event.setEventName("accessed-job");
//            event.putMetadata("applicant-count", job.getNoOfCandidatesApplied());
//            event.putMetadata("shortlisted-count", job.getNoOfCandidatesShortlisted());
//            event.setUserID(user.getUserId());
//            event.setCreatedAt(currentTimeMillis()/1000L);
//
//            Event.create(event);
//        }   
//        catch (Exception e)
//        {
//            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while creating accessed job event in intercom");
//            
//        }
//    }
}
