import { ICasePayload, IRecommendation, IRecommendationTrack, IStrataAccountResponse } from '@rh-support/api';
import { IPortalJwtToken } from '@rh-support/types';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import uniqBy from 'lodash/uniqBy';
import CaseUtils from '../utils/caseUtils';
import { ICreateCaseState, ITRForSLASeverity, KtQuestionConstant, SupportLevelsInternal } from './CreateCaseReducer';

export const getCaseRecommendations = (docs: IRecommendation[], oldDocs) => {
    const recs = [];
    docs.forEach((doc, i) => {
        recs.push(getRecommendationObject(doc, i));
    });
    return uniqBy([...recs, ...oldDocs], 'resourceId');
};

const getRecommendationObject = (doc: IRecommendation, index: number) => {

    const bucket = index === 0 ? 4 : 3;
    const rec: IRecommendationTrack = {
        resourceId: doc.id,
        resourceURI: doc.uri,
        resourceViewURI: doc.view_uri,
        title: doc.publishedTitle || doc.allTitle,
        resourceType: doc.documentKind,
        client: 'solution-engine-app',
        clientVersion: window.seVersionInfo.gitTag,
        analysisAlgorithm: 'Text Analysis',
        analysisService: 'calaveras',
        algorithmScore: doc.score,
        resource: 'Summary',
        analysisCategory: 'Text Analysis',
        bucket
    };

    if (doc.documentKind === 'Solution') {
        rec.solutionOwnerSSOName = doc.authorSSOName;
        rec.solutionAbstract = doc.publishedAbstract || doc.abstract;
        rec.solutionTitle = doc.publishedTitle || doc.allTitle;
        rec.solutionKcsState = doc.kcsState;
        rec.solutionUrl = doc.view_uri;
    }
    return rec;
};

export const getUpdatedDescription = (issue: string, environment?: string, periodicityOfIssue?: string, timeFramesAndUrgency?: string): string => {
    let description = issue;
    if (!isEmpty(environment) || !isEmpty(periodicityOfIssue) || !isEmpty(timeFramesAndUrgency)) {
        description = `${KtQuestionConstant.issue}\n${issue}`;
        description +=  !isEmpty(environment) ? `\n\n${KtQuestionConstant.environment}\n${environment}` : '';
        description +=  !isEmpty(periodicityOfIssue) ? `\n\n${KtQuestionConstant.periodicityOfIssue}\n${periodicityOfIssue}` : '';
        description +=  !isEmpty(timeFramesAndUrgency) ? `\n\n${KtQuestionConstant.timeFramesAndUrgency}\n${timeFramesAndUrgency}` : '';
    }
    return description;
};

export const getDescriptionWOQues = (issue: string, environment?: string, periodicityOfIssue?: string, timeFramesAndUrgency?: string): string => {
    let description = issue;
    if (!isEmpty(environment) || !isEmpty(periodicityOfIssue) || !isEmpty(timeFramesAndUrgency)) {
        description +=  !isEmpty(environment) ? ` ${environment}` : '';
        description +=  !isEmpty(periodicityOfIssue) ? ` ${periodicityOfIssue}` : '';
        description +=  !isEmpty(timeFramesAndUrgency) ? ` ${timeFramesAndUrgency}` : '';
    }
    return description;
};

export const getIrtForSLAAndSeverity = (sla: string, severity: string): string => {
    if (isEmpty(sla) || isEmpty(severity)) { return ''; }
    const supportLevel = CaseUtils.isPremiumEntitlement(sla) ? SupportLevelsInternal.PREMIUM : SupportLevelsInternal.STANDARD;
    return ITRForSLASeverity[supportLevel][severity].initialAndOngoing || ITRForSLASeverity[supportLevel][severity].initial;
};

export const isCaseStateValid = (createCaseState: ICreateCaseState, require_cgroup_on_create: boolean, loggedInUserJwtToken: Partial<IPortalJwtToken>): boolean => {
    return  isEmpty(createCaseState.caseNumber) && !createCaseState.hasLargeCaseDescription
    && !isEmpty(createCaseState.product) && !isEmpty(createCaseState.version)
    && !isEmpty(createCaseState.summary)
    && !isEmpty(createCaseState.description)
    && !isEmpty(createCaseState.type)
    && !isEmpty(createCaseState.severity)
    && (require_cgroup_on_create ?
        !isEmpty(createCaseState.folderNumber) ||  createCaseState.folderNumber !== '-1' : true)
    && CaseUtils.canManageCase(loggedInUserJwtToken);
};

export const createCasePayload = (caseDetails: ICreateCaseState, loggedInUsersAccount: Partial<IStrataAccountResponse>): Partial<ICasePayload> => {
    const casePayload: Partial<ICasePayload> = {};
    !isEmpty(caseDetails.accountNumber) && (casePayload.accountNumber = caseDetails.accountNumber);
    !isEmpty(caseDetails.contactSsoUsername) && (casePayload.contactSsoUsername = caseDetails.contactSsoUsername);
    !isEmpty(caseDetails.product) && (casePayload.product = caseDetails.product);
    !isEmpty(caseDetails.version) && (casePayload.version = caseDetails.version);
    !isEmpty(caseDetails.summary) && (casePayload.summary = caseDetails.summary);
    !isEmpty(caseDetails.description) && (casePayload.description = caseDetails.description);
    !isEmpty(caseDetails.type) && (casePayload.type = caseDetails.type);
    !isEmpty(caseDetails.entitlement) && (casePayload.entitlement = caseDetails.entitlement);
    !isEmpty(caseDetails.severity) && (casePayload.severity = caseDetails.severity);
    !isEmpty(caseDetails.folderNumber) && (casePayload.folderNumber = caseDetails.folderNumber);
    !isEmpty(caseDetails.language) && (casePayload.language = caseDetails.language);
    !isEmpty(caseDetails.recommendations.recommendation) && (casePayload.recommendations = caseDetails.recommendations);
    if (loggedInUsersAccount.has_enhanced_sla && loggedInUsersAccount.has_available_enhanced_sla && !isEmpty(caseDetails.enhancedSLA)) {
        casePayload.enhancedSLA = !!caseDetails.enhancedSLA;
    }
    if (CaseUtils.showFts(get(caseDetails.entitlement, 'sla', ''), caseDetails.severity)) {
        casePayload.fts = !!caseDetails.fts;
        if (caseDetails.fts) {
            casePayload.contactInfo24X7 = caseDetails.contactInfo24X7;
        }
    }
    // check and set kt questions
    !isEmpty(caseDetails.issue) && (
        !isEmpty(caseDetails.environment) ||
        !isEmpty(caseDetails.periodicityOfIssue) ||
        !isEmpty(caseDetails.timeFramesAndUrgency)
    ) && (casePayload.issue = caseDetails.issue);
    !isEmpty(caseDetails.environment) && (casePayload.environment = caseDetails.environment);
    !isEmpty(caseDetails.periodicityOfIssue) && (casePayload.periodicityOfIssue = caseDetails.periodicityOfIssue);
    !isEmpty(caseDetails.timeFramesAndUrgency) && (casePayload.timeFramesAndUrgency = caseDetails.timeFramesAndUrgency);
    return casePayload;
};
