import Immutable from 'immutable';
import _ from 'lodash';

import AuthStore from 'stores/Auth';
import DepartmentStore from 'stores/Departments';
import UserStore from 'stores/Users';
import Url from 'lib/Url';

import departmentAvatarIcon from '../../static/i/department-avatar.svg';

const DEFAULTS = {
    id: undefined,
    label: undefined,
    email: undefined,
    head: undefined,
    name: undefined,
    description: undefined,
    removed: undefined,
    parent: undefined,
    parents: undefined,
    is_outstaff: undefined,
    members_count: undefined,
};

class Department extends Immutable.Record(DEFAULTS) {
    static PRIMARY_KEY = 'id';
    static TYPE_NAME = 'department';

    static getAvatar() {
        return departmentAvatarIcon;
    }

    static create(data) {
        const nextData = _.pick(data, Object.keys(DEFAULTS));

        if (nextData.id !== undefined && nextData.id !== null) {
            nextData.id = String(nextData.id);
        }

        return new Department(Immutable.fromJS(nextData));
    }

    getId() {
        return this.get(Department.PRIMARY_KEY);
    }

    getType() {
        return Department.TYPE_NAME;
    }

    equals(x) {
        return (x instanceof Department) && x.getId() === this.getId();
    }

    getUrl() {
        return Url.getContextPath(`${this.getType()}s`, this.getId());
    }

    _getLocalized(path, locale) {
        locale = locale || AuthStore.getLocale();

        let value = this.getIn(path);

        if (value && typeof value !== 'string' && value.get) {
            value = value.get(locale);
        }

        return value;
    }

    getName(locale) {
        return this._getLocalized(['name'], locale || AuthStore.getLocale()) ||
            this._getLocalized(['name'], 'en') ||
            this._getLocalized(['name'], 'ru');
    }

    toSortableString(locale) {
        return (this.getName(locale) || '').toLowerCase();
    }

    getDescription(locale) {
        return this._getLocalized(['description'], locale || AuthStore.getLocale()) ||
            this._getLocalized(['description'], 'en') ||
            this._getLocalized(['description'], 'ru');
    }

    getHead() {
        return UserStore.get(this.get('head'));
    }

    getParent() {
        return DepartmentStore.get(this.get('parent'));
    }

    getParents() {
        return (this.get('parents') || []).map(id => DepartmentStore.get(id));
    }

    getMemberCount() {
        return this.get('members_count');
    }

    getAvatar() {
        return departmentAvatarIcon;
    }

    getEmail() {
        let email = this.get('email');
        let label = this.get('label');

        return email || (label && `${label}@${AuthStore.getOrganizationDomain()}`);
    }

    isRoot() {
        return !this.getParent();
    }

    isOutstaff() {
        return this.get('is_outstaff');
    }

    isEmpty() {
        return this.get('members_count') === 0;
    }
}

export default Department;
