package com.info08.billing.callcenter.client.dialogs.correction;

import com.info08.billing.callcenter.client.CallCenter;
import com.info08.billing.callcenter.client.singletons.MapUtil;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.TitleOrientation;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class DlgAddEditAbPhone extends Window {

	private VLayout hLayout;
	private DynamicForm formPhone;
	private TextItem phoneItem;
	private ComboBoxItem isHideItem;
	private ComboBoxItem isParallelItem;
	private ComboBoxItem phoneStatusItem;
	private ComboBoxItem phoneStateItem;
	private ComboBoxItem phoneTypeItem;
	private ListGrid listGridPhones;

	// private ListGridRecord listGridRecord;
	// private DataSource phonesDS;

	public DlgAddEditAbPhone(final ListGridRecord listGridRecord,
			ListGrid listGridPhones) {
		this.listGridPhones = listGridPhones;
		// this.listGridRecord = listGridRecord;
		// this.phonesDS = phonesDS;
		setWidth(750);
		setHeight(150);
		setTitle(listGridRecord == null ? "ახალი ნომრის დამატება"
				: "ნომრის შესწორება");
		setShowMinimizeButton(false);
		setIsModal(true);
		setShowModalMask(true);
		setCanDrag(false);
		setCanDragReposition(false);
		setCanDragResize(false);
		setCanDragScroll(false);
		centerInPage();

		hLayout = new VLayout(5);
		hLayout.setWidth100();
		hLayout.setHeight100();

		formPhone = new DynamicForm();
		formPhone.setPadding(10);
		formPhone.setAutoFocus(true);
		formPhone.setWidth100();
		formPhone.setTitleWidth(80);
		formPhone.setNumCols(7);
		formPhone.setTitleOrientation(TitleOrientation.TOP);

		phoneItem = new TextItem();
		phoneItem.setTitle("ტელეფონი");
		phoneItem.setName("phone");
		phoneItem.setWidth(170);

		isHideItem = new ComboBoxItem();
		isHideItem.setValueMap(MapUtil.getInstance().getMapOpClose());
		isHideItem.setDefaultToFirstOption(true);
		isHideItem.setTitle("ღია/დაფარული");
		isHideItem.setName("is_hide");
		isHideItem.setWidth(112);

		isParallelItem = new ComboBoxItem();
		isParallelItem.setValueMap(MapUtil.getInstance().getMapParall());
		isParallelItem.setDefaultToFirstOption(true);
		isParallelItem.setTitle("პარალელური");
		isParallelItem.setName("is_parallel");
		isParallelItem.setWidth(120);

		phoneStatusItem = new ComboBoxItem();
		phoneStatusItem.setValueMap(MapUtil.getInstance().getMapStatuses());
		phoneStatusItem.setDefaultToFirstOption(true);
		phoneStatusItem.setTitle("სტატუსი");
		phoneStatusItem.setName("phone_status_id");
		phoneStatusItem.setWidth(100);

		phoneStateItem = new ComboBoxItem();
		phoneStateItem.setValueMap(MapUtil.getInstance().getMapStates());
		phoneStateItem.setDefaultToFirstOption(true);
		phoneStateItem.setTitle("მდგომარეობა");
		phoneStateItem.setName("phone_state_id");
		phoneStateItem.setWidth(100);

		phoneTypeItem = new ComboBoxItem();
		phoneTypeItem.setValueMap(MapUtil.getInstance().getMapTypes());
		phoneTypeItem.setDefaultToFirstOption(true);
		phoneTypeItem.setTitle("ტიპი");
		phoneTypeItem.setName("phone_type_id");
		phoneTypeItem.setWidth(119);

		if (listGridRecord != null) {
			phoneItem.setValue(listGridRecord.getAttribute("phone"));
			isHideItem.setValue(listGridRecord.getAttribute("is_hide"));
			isParallelItem.setValue(listGridRecord.getAttribute("is_parallel"));
			phoneStatusItem.setValue(listGridRecord
					.getAttribute("phone_status_id"));
			phoneStateItem.setValue(listGridRecord
					.getAttribute("phone_state_id"));
			phoneTypeItem
					.setValue(listGridRecord.getAttribute("phone_type_id"));
		}

		formPhone.setFields(phoneItem, isHideItem, isParallelItem,
				phoneStatusItem, phoneStateItem, phoneTypeItem);

		HLayout hLayoutItem = new HLayout(5);
		hLayoutItem.setWidth100();
		hLayoutItem.setAlign(Alignment.RIGHT);
		hLayoutItem.setMargin(10);

		IButton saveItem = new IButton();
		saveItem.setTitle("შენახვა");
		saveItem.setWidth(100);

		IButton cancItem = new IButton();
		cancItem.setTitle("დახურვა");
		cancItem.setWidth(100);

		hLayoutItem.setMembers(saveItem, cancItem);
		hLayout.setMembers(formPhone, hLayoutItem);
		addItem(hLayout);

		cancItem.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				destroy();
			}
		});

		saveItem.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				addRecord(listGridRecord);
			}
		});
	}

	private void addRecord(ListGridRecord listGridRecord) {
		try {
			Object oPhone = phoneItem.getValue();
			if (oPhone == null || oPhone.toString().trim().equals("")) {
				SC.say("გთხოვთ შეიყვანოთ ტელეფონის ნომერი !");
				return;
			}
			Integer phone = null;
			try {
				phone = Integer.parseInt(oPhone.toString());
			} catch (Exception e) {
				SC.say("არასწორი ტელეფონის ნომერი " + oPhone.toString()
						+ " !. ტელეფონის ნომერი შედგება მხოლოდ ციფრებისაგან. ");
				return;
			}
			Object opClose = isHideItem.getValue();
			if (opClose == null) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის ნომერი ღიაა თუ დაფარული !");
				return;
			}
			Integer iOpClose = null;
			try {
				iOpClose = Integer.parseInt(opClose.toString());
			} catch (NumberFormatException e) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის ნომერი ღიაა თუ დაფარული !");
				return;
			}
			Object paralelUsual = isParallelItem.getValue();
			if (paralelUsual == null) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის ნომერი პარალელურია თუ ჩვეულებრივი !");
				return;
			}
			Integer iParalelUsual = null;
			try {
				iParalelUsual = Integer.parseInt(paralelUsual.toString());
			} catch (NumberFormatException e) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის ნომერი პარალელურია თუ ჩვეულებრივი !");
				return;
			}
			Object phoneStatus = phoneStatusItem.getValue();
			if (phoneStatus == null) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის სტატუსი !");
				return;
			}
			Integer iPhoneStatus = null;
			try {
				iPhoneStatus = Integer.parseInt(phoneStatus.toString());
			} catch (NumberFormatException e) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის სტატუსი !");
				return;
			}

			Object phoneState = phoneStateItem.getValue();
			if (phoneState == null) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის მდგომარეობა !");
				return;
			}
			Integer iPhoneState = null;
			try {
				iPhoneState = Integer.parseInt(phoneState.toString());
			} catch (NumberFormatException e) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის მდგომარეობა !");
				return;
			}

			Object phoneType = phoneTypeItem.getValue();
			if (phoneType == null) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის ტიპი !");
				return;
			}
			Integer iPhoneType = null;
			try {
				iPhoneType = Integer.parseInt(phoneType.toString());
			} catch (NumberFormatException e) {
				SC.say("გთხოვთ აირჩიოთ ტელეფონის ტიპი !");
				return;
			}
			boolean isAdd = false;
			if (listGridRecord == null) {
				listGridRecord = new ListGridRecord();
				isAdd = true;
			}
			ListGridRecord records[] = listGridPhones.getRecords();
			if (records != null && records.length > 0) {
				for (ListGridRecord record : records) {
					if (listGridRecord.equals(record)) {
						continue;
					}
					String rPhone = record.getAttribute("phone");
					if (rPhone == null) {
						continue;
					}
					if (rPhone.equals(phone.toString())) {
						SC.say("ასეთი ნომერი უკვე მინიჭებულია ამ აბონენტისათვის");
						return;
					}
				}
			}
			doSave(listGridRecord, phone, iOpClose, iParalelUsual,
					iPhoneStatus, iPhoneState, iPhoneType, isAdd);

		} catch (Exception e) {
			e.printStackTrace();
			SC.say(e.toString());
		}
	}

	private void doSave(final ListGridRecord listGridRecord,
			final Integer phone, final Integer iOpClose,
			final Integer iParalelUsual, final Integer iPhoneStatus,
			final Integer iPhoneState, final Integer iPhoneType,
			final boolean isAdd1) {
		try {
			DataSource dataSource = DataSource.get("AbPhonesDS");
			Criteria criteria = new Criteria();
			criteria.setAttribute("phone", phone.toString());
			DSRequest req = new DSRequest();
			req.setAttribute("operationId", "getPhone");
			dataSource.fetchData(criteria, new DSCallback() {
				@Override
				public void execute(DSResponse response, Object rawData,
						DSRequest request) {
					Record records[] = response.getData();
					if (records != null && records.length > 0) {
						Record record = records[0];
						SC.say("ეს ნომერი უკვე მინიჭებულია აბონენტისათვის : "
								+ record.getAttribute("firstname".toUpperCase())
								+ " "
								+ record.getAttribute("lastname".toUpperCase())
								+ ", ნომერი - " + record.getAttribute("phone"));
						return;
					} else {
						listGridRecord.setAttribute("phone", phone.toString());
						listGridRecord.setAttribute("is_hide", iOpClose);
						listGridRecord.setAttribute("is_parallel",
								iParalelUsual);
						listGridRecord.setAttribute("phone_status_id",
								iPhoneStatus);
						listGridRecord.setAttribute("phone_state_id",
								iPhoneState);
						listGridRecord
								.setAttribute("phone_type_id", iPhoneType);
						listGridRecord.setAttribute(
								"is_hide_descr",
								MapUtil.getInstance().getMapOpClose()
										.get(iOpClose.toString()));
						listGridRecord.setAttribute(
								"is_parallel_descr",
								MapUtil.getInstance().getMapParall()
										.get(iParalelUsual.toString()));
						listGridRecord.setAttribute(
								"phone_status",
								MapUtil.getInstance().getMapStatuses()
										.get(iPhoneStatus.toString()));
						listGridRecord.setAttribute(
								"phone_state",
								MapUtil.getInstance().getMapStates()
										.get(iPhoneState.toString()));
						listGridRecord.setAttribute(
								"phone_type",
								MapUtil.getInstance().getMapTypes()
										.get(iPhoneType.toString()));
						listGridRecord.setAttribute("loggedUserName",
								CallCenter.sessionPerson.getUserName());
						listGridRecord.setAttribute("deleted", 0);

						if (isAdd1) {
							listGridPhones.addData(listGridRecord);
						} else {
							listGridPhones.updateData(listGridRecord);
						}
						destroy();
					}
				}

			}, req);
		} catch (Exception e) {
			SC.say(e.toString());
		}
	}
}
