/**
 * Тип записи для выдачи из саджеста
 */
import _ from 'lodash';
import Immutable from 'immutable';
import Url from 'lib/Url';
import ConfigStore from 'stores/Config';
import AuthStore from 'stores/Auth';

import User from 'records/User';

const DEFAULTS = {
    id: undefined,
    type: undefined,
    title: undefined,
    avatar: undefined,
    description: undefined,
    nickname: undefined,
    search_item: true,
};

class SearchItem extends Immutable.Record(DEFAULTS) {
    static PRIMARY_KEY = 'id';

    static create(data) {
        const nextData = _.extend({}, data);

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

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

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

    getType() {
        return this.get('type');
    }

    getName() {
        return this.get('title');
    }

    getNickname() {
        return this.get('nickname');
    }

    getSortableName() {
        return this.getName();
    }

    getDescription() {
        return this.get('description');
    }

    getAvatar() {
        return this.get('avatar');
    }

    getExternalStaffUrl() {
        return Url.build(ConfigStore.get('ui.staff'), {
            nickname: this.getNickname(),
            org_id: AuthStore.getOrganizationId(),
            uid: this.getId(),
        });
    }

    equals(record) {
        return record.getType() === this.getType() && record.getId() === this.getId();
    }

    getUrl() {
        if (this.getType() === User.TYPE_NAME &&
            ConfigStore.get('ui.staffModeEnabled') &&
            AuthStore.getViewMode() !== 'admin') {
            return this.getExternalStaffUrl();
        }

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

export default SearchItem;
