package ee.ut.math.tvt2008.salessystem.ui.model;

import ee.ut.math.tvt2008.salessystem.domain.data.Client;
import ee.ut.math.tvt2008.salessystem.util.Translations;
import org.hibernate.Transaction;
import org.hibernate.Session;

/**
 * Client model.
 */
public class ClientTableModel extends SalesSystemTableModel<Client> {

    private static final long serialVersionUID = 1L;
    private Session session;

    public ClientTableModel() {
        super(new String[]{
                    Translations.getString("main.id"),
                    Translations.getString("main.firstname"),
                    Translations.getString("main.lastName"),
                    Translations.getString("main.discount")
                });
    }
    
    public ClientTableModel(Session session) {
        this();
        this.session = session;
    }
    
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if(columnIndex>2)return true;
        else return false;
    }

    @Override
    public void setValueAt(Object value, int rowIndex, int columnIndex) {
        Client changeable = rows.get(rowIndex);
        try {
            switch (columnIndex) {
                case 3:
                    Integer discount = Integer.parseInt((String) value);
                    if((discount >= 0)&&(discount <= 100))
                    changeable.setDiscountPercentage(discount);
                    break;
                default:
                    return;
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        Transaction tx = session.beginTransaction();
        session.save(changeable);
        tx.commit();
    }

    @Override
    protected Object getColumnValue(Client client, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return client.getId();
            case 1:
                return client.getFirstName();
            case 2:
                return client.getLastName();
            case 3:
                return client.getDiscountPercentage();
        }
        throw new IllegalArgumentException("Column index out of range");
    }

    @Override
    public String toString() {
        final StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < headers.length; i++) {
            buffer.append(headers[i] + "\t");
        }
        buffer.append("\n");

        for (final Client client : rows) {
            buffer.append(client.getId() + "\t");
            buffer.append(client.getFirstName() + "\t");
            buffer.append(client.getDiscountPercentage() + "\t");
            buffer.append("\n");
        }

        return buffer.toString();
    }
}
