package performa.intercom.utils;

import java.util.HashMap;
import java.util.Map;
import oneit.appservices.config.ConfigMgr;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.security.SecUser;
import performa.intercom.resources.Company;
import performa.intercom.resources.CustomAttribute;
import performa.intercom.resources.Intercom;
import performa.intercom.resources.User;


public class IntercomUtils 
{
    static
    {
        Intercom.setToken(ConfigMgr.getKeyfileString("intercom.token", ""));
    }
    
    
    public static User createIntercomUser(SecUser secUser, String role, Company company)
    {
        try
        {        
            User    user = new User();
                                
            user.setUserId(secUser.getIdentification());
            user.setEmail(secUser.getUserName());
            user.setName(secUser.getName());
            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 Company createIntercomCompany(performa.orm.Company company)
    {
        try
        {        
            Company intercomCompany =   new Company();
                                                
            intercomCompany.setName(company.getCompanyName());
            intercomCompany.setCompanyID(company.getID().toString());
            
            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());

            Company intercomCompany =   Company.find(map);
            
            if(intercomCompany == null)
            {
                intercomCompany =   createIntercomCompany(company);
            }
            
            return intercomCompany;
        }
        catch (Exception e)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while fetching a company by id from intercom");
            
            return null;
        }
    }
}
