/*
CreditCardJS
(c) 2017-2018 Erwin Paydar
https://github.com/CyberPy/CreditCardJS
License: All Rights Reserved
*/

class CreditCard extends Classic
{
    constructor(cc)
    {
        super();
        this.cc = cc;
    }

    self_reduce(self, num)
    {
        if(num > 9)
        {
            num -= 9;
        }
        return num;
    }

    self_double(self, i)
    {
        if (i % 2 !== 0)
        {
            self.cc[i] = self.reduce(self.cc[i] * 2);
        }
    }

    self_iterate(self)
    {
        for (var i in self.cc)
        {
            self.double(i);
        }
    }

    self_add(self)
    {
        self.cc = self.cc.reduce((x, y) => x + y, 0);
    }

    self_validate(self)
    {
        self.iterate();
        self.add();
        return self.cc % 10 === 0;
    }

    self_filter(self)
    {
        self.cc = self.cc.replace(' ', '');
        self.cc = self.cc.replace('-', '');
        self.cc = self.cc.split('');
        for(var i in self.cc)
        {
            self.cc[i] = Number(self.cc[i]);
        }
        self.cc.reverse();
    }

    self_check(self)
    {
        var valid;
        if(typeof(self.cc) === 'string')
        {
            self.filter();
            valid = self.validate();
        }
        else
        {
            valid = false;
        }
        return valid;
    }
}