/*
 * Copyright (c) 2002-2004
 * All rights reserved.
 */

package com.atlassian.jira.util;

import com.atlassian.core.ofbiz.CoreFactory;
import com.atlassian.core.ofbiz.util.EntityUtils;
import com.atlassian.jira.issue.index.IndexException;
import com.atlassian.jira.issue.index.IssueIndexManager;
import com.atlassian.jira.issue.cache.CacheManager;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.IssueFactory;
import com.atlassian.jira.issue.comments.CommentManager;
import com.atlassian.jira.issue.customfields.manager.OptionsManager;
import com.atlassian.jira.issue.fields.screen.issuetype.IssueTypeScreenSchemeManager;
import com.atlassian.core.util.map.EasyMap;
import com.atlassian.jira.web.action.util.DatabaseConnectionBean;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.project.version.VersionManager;
import com.atlassian.jira.permission.PermissionSchemeManager;
import com.atlassian.jira.security.PermissionManager;
import com.atlassian.jira.external.ExternalUtils;
import com.atlassian.jira.bc.project.component.ProjectComponentManager;
import com.atlassian.jira.bc.project.ProjectService;
import com.atlassian.jira.user.util.UserUtil;
import com.opensymphony.user.User;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericDelegator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * A variant of the MantisImportBean meeting some special customer requirements:
 * <ol>
 * <li>A log (/tmp/attachments.txt) is kept of where attachments are created.
 * <li>Normally, features will be set to priority 'major'.  In this importer, features are set to a custom priority, 'Mantis - Feature'.
 * <li>JIRA usernames are derived from the email address (from 'joe.bloggs@foo.com', we get 'joe.bloggs').
 * </ol>
 */
public class CustomMantisImportBean extends MantisImportBean
{
    private static final String ATTACHMENTS_LOGFILE = "/tmp/attachments.txt";
    private String nextPriorityId;

    public CustomMantisImportBean(IssueIndexManager indexManager, GenericDelegator genericDelegator, ProjectManager projectManager, PermissionSchemeManager permissionSchemeManager, CacheManager cacheManager, IssueManager issueManager, VersionManager versionManager, ProjectComponentManager projectComponentManager, CustomFieldManager customFieldManager, IssueTypeScreenSchemeManager issueTypeScreenSchemeManager, PermissionManager permissionManager, OptionsManager optionsManager, ExternalUtils externalUtils, CommentManager commentManager, IssueFactory issueFactory, ProjectService projectService, UserUtil userUtil)
    {
        super(indexManager, genericDelegator, projectManager, permissionSchemeManager, cacheManager, issueManager, versionManager, projectComponentManager, customFieldManager, issueTypeScreenSchemeManager, permissionManager, optionsManager, externalUtils, commentManager, issueFactory, projectService, userUtil);
    }

    public void doImport(MantisImportBean.MappingBean mappingBean, DatabaseConnectionBean connectionBean, boolean enableNotifications, boolean reuseExistingUsers, boolean addToDevelopersGroup, boolean reindex, String[] projectNames, User importer) throws Exception, IndexException, GenericEntityException
    {
        createPriority("Mantis - Feature");
        resetAttachmentLog();
        super.doImport(mappingBean, connectionBean, enableNotifications, reuseExistingUsers, addToDevelopersGroup, reindex, projectNames, importer);
    }

    private void createPriority(String priorityName) throws GenericEntityException
    {
        if (CoreFactory.getGenericDelegator().findByAnd("Priority", EasyMap.build("name", priorityName)).size() == 0)
        {
            nextPriorityId = EntityUtils.getNextStringId("Priority");

            Map fields = new HashMap();
            fields.put("id", nextPriorityId);
            fields.put("name", priorityName);
            fields.put("description", "A Mantis feature");
            fields.put("iconurl", "/images/icons/priority_major.gif");
            fields.put("sequence", new Long(6)); // todo: unhardcode
            EntityUtils.createValue("Priority", fields);
        }
    }

    protected int getMantisFeaturePriority()
    {
        return Integer.parseInt(nextPriorityId);
    }

    /**
     * "We would like to have all user names follow the name.lastname convention ("joe.bloggs") even when in Mantis
     * they may use shortcuts ("joe"). This is important as we have an increasing number of Daves and Stephens !"
     */
    protected String getMantisUsername(ResultSet resultSet) throws SQLException
    {
        String email = resultSet.getString("email");
        String username = resultSet.getString("username");

        if (email == null)
            return "";
        if (email.indexOf('@') == -1)
            return username;

        String firstPart = email.substring(0, email.indexOf('@'));
        int i = firstPart.indexOf('.');
        if (i == -1)
            return username;
        else if (i + 1 <= firstPart.length() && firstPart.length() > 2)
        {
            return firstPart;
        }
        else
            return username;
    }

    protected void logAttachmentLocation(String diskfile, File jiraAttachFile) throws IOException
    {
        FileWriter fw = new FileWriter(ATTACHMENTS_LOGFILE, true);
        fw.write("\n" + diskfile + "," + jiraAttachFile.getCanonicalPath());
        fw.close();
    }

    protected void resetAttachmentLog()
    {
        new File(ATTACHMENTS_LOGFILE).delete();
    }
}
