import { Model } from 'front';

// Checks that the credit card number is valid using Luhn algorithm
const luhnCheck = (function(arr) {
    return function(ccNum) {
        let len = ccNum.length,
            bit = 1,
            sum = 0,
            val;

        while (len) {
            val = parseInt(ccNum.charAt(--len), 10);
            sum += (bit ^= 1) ? arr[val] : val;
        }

        return sum && sum % 10 === 0;
    };
})([ 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 ]);

/**\

    title: CreditCard
    category: model
    description: A model for credit cards

\**/
class CreditCard extends Model {
    static getCardType(number) {
        if (number.match(/^4/)) {
            return 'visa';
        }

        if (number.match(/^5[1-5]/)) {
            return 'mastercard';
        }

        if (number.match(/^3[47]/)) {
            return 'american-express';
        }

        if (number.match(/^6(?:011|5)/)) {
            return 'discover';
        }

        if (number.match(/^(?:2131|1800|35)/)) {
            return 'jcb';
        }

        if (number.match(/^3(?:0[0-5]|[68])/)) {
            return 'diners-club';
        }

        if (number.match(/^5018|5020|5038|5893|6304|67(59|61|62|63)|0604/)) {
            return 'maestro';
        }

        return '';
    }

    static checkValid(number) {
        return luhnCheck('' + number);
    }

    constructor(data) {
        super({
            uuid: '',
            label: '',

            number: '',
            month: null, // number 1-12
            year: null, // 4 digit year
            cvv: '',
            zip: '',

            type: '',
            lastFour: ''
        });

        this.fill(data);
    }

    fill(data) {
        super.fill(data);

        if (!(data && typeof data === 'object')) {
            return;
        }

        if (typeof data.number === 'string') {
            this.lastFour = data.number.slice(-4);
        }

        if (CreditCard.checkValid(data.number)) {
            this.type = CreditCard.getCardType(data.number);
        }
    }
}

export default CreditCard;
