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



public class DlgAddEditAbonent extends Window {

	private VLayout hLayout;
	private DynamicForm formPersInfo;
	private DynamicForm formAddress;
	private DynamicForm formAddressParams;
	private ComboBoxItem firstNameItem;
	private ComboBoxItem lastNameItem;
	private TextItem oldAddItem;
	private ComboBoxItem citiesItem;
	private ComboBoxItem streetItem;
	private ComboBoxItem regionItem;
	private ComboBoxItem adressOpCloseItem;
	private TextItem adressItem;
	private TextItem blockItem;
	private TextItem appartItem;
	private TextItem addrAddInfoItem;
	private TextAreaItem streetDescrItem;
	private DataSource abonentsDS;
	private ListGrid listGridPhones;

	public DlgAddEditAbonent(final Abonent abonent, DataSource abonentsDS) {
		this.abonentsDS = abonentsDS;

		setWidth(750);
		setHeight(700);
		setTitle(abonent == null ? "ახალი აბონენტის დამატება"
				: "აბონენტის მოდიფიცირება");
		setShowMinimizeButton(false);
		setIsModal(true);
		setShowModalMask(true);
		setCanDrag(false);
		setCanDragReposition(false);
		setCanDragResize(false);
		setCanDragScroll(false);
		centerInPage();

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

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

		HeaderItem headerItemPersInfo = new HeaderItem();
		headerItemPersInfo.setValue("აბონენტის პირადი ინფორმაცია");
		headerItemPersInfo.setTextBoxStyle("headerStyle");

		firstNameItem = new ComboBoxItem();
		firstNameItem.setTitle("სახელი");
		firstNameItem.setName("firstname");
		firstNameItem.setWidth(270);

		lastNameItem = new ComboBoxItem();
		lastNameItem.setTitle("გვარი");
		lastNameItem.setName("lastname");
		lastNameItem.setWidth(324);

		HiddenItem abonentIdItem = null;
		if (abonent != null) {
			firstNameItem.setValue(abonent.getFirstname());
			lastNameItem.setValue(abonent.getLastname());
			abonentIdItem = new HiddenItem();
			abonentIdItem.setValue(abonent.getAbonent_id());
			abonentIdItem.setName("abonent_id");
			abonentIdItem.setVisible(false);

			formPersInfo.setFields(headerItemPersInfo, firstNameItem,
					lastNameItem, abonentIdItem);
		} else {
			formPersInfo.setFields(headerItemPersInfo, firstNameItem,
					lastNameItem);
		}

		final AbPhonesClientDS abPhonesClientDS = AbPhonesClientDS
				.getInstance();

		listGridPhones = new ListGrid();
		listGridPhones.setHeight(150);
		listGridPhones.setWidth100();
		listGridPhones.setDataSource(abPhonesClientDS);
		listGridPhones.setDataPageSize(50);
		listGridPhones.setAutoFetchData(true);
		listGridPhones.setSelectionType(SelectionStyle.SINGLE);

		listGridPhones.setUseAllDataSourceFields(true);

		formAddress = new DynamicForm();
		formAddress.setPadding(10);
		formAddress.setAutoFocus(false);
		formAddress.setWidth100();
		formAddress.setTitleWidth(80);
		formAddress.setNumCols(3);
		formAddress.setTitleOrientation(TitleOrientation.TOP);
		formAddress.setCanDragResize(false);

		HeaderItem headerItemAddr = new HeaderItem();
		headerItemAddr.setValue("აბონენტის მისამართი");
		headerItemAddr.setTextBoxStyle("headerStyle");

		citiesItem = new ComboBoxItem();
		citiesItem.setTitle("ქალაქი");
		citiesItem.setName("city_name_geo");
		citiesItem.setWidth(170);

		streetItem = new ComboBoxItem();
		streetItem.setTitle("ქუჩა");
		streetItem.setName("street_name_geo");
		streetItem.setWidth(322);

		regionItem = new ComboBoxItem();
		regionItem.setTitle("უბანი");
		regionItem.setName("city_region_name_geo");
		regionItem.setWidth(217);

		streetDescrItem = new TextAreaItem();
		streetDescrItem.setTitle("ქუჩის აღწერა");
		streetDescrItem.setName("streetDescrItem");
		streetDescrItem.setWidth(709);
		streetDescrItem.setColSpan(3);
		streetDescrItem.setHeight(50);
		streetDescrItem.setDisabled(true);

		formAddress.setFields(headerItemAddr, citiesItem, streetItem,
				regionItem, streetDescrItem);

		formAddressParams = new DynamicForm();
		formAddressParams.setPadding(10);
		formAddressParams.setAutoFocus(false);
		formAddressParams.setWidth100();
		formAddressParams.setNumCols(6);
		formAddressParams.setTitleOrientation(TitleOrientation.TOP);

		HeaderItem headerItemAddrParams = new HeaderItem();
		headerItemAddrParams.setValue("მისამართის პარამეტრები");
		headerItemAddrParams.setTextBoxStyle("headerStyle");

		oldAddItem = new TextItem();
		oldAddItem.setTitle("ძველი მისამართი");
		oldAddItem.setName("oldAddItem");
		oldAddItem.setWidth(440);
		oldAddItem.setColSpan(6);
		oldAddItem.setDisabled(true);
		oldAddItem.setValue("აქ იქნება ძველი მისამართი");

		adressOpCloseItem = new ComboBoxItem();
		LinkedHashMap<String, String> addrMapOpClose = new LinkedHashMap<String, String>();
		addrMapOpClose.put("0", "ღია");
		addrMapOpClose.put("1", "დაფარულია");
		adressOpCloseItem.setValueMap(addrMapOpClose);
		adressOpCloseItem.setDefaultToFirstOption(true);
		adressOpCloseItem.setTitle("ღია/დაფარული");
		adressOpCloseItem.setName("adressOpCloseItem");
		adressOpCloseItem.setWidth(170);

		adressItem = new TextItem();
		adressItem.setTitle("სახლი");
		adressItem.setName("sdasdadressItem");
		adressItem.setWidth(110);

		blockItem = new TextItem();
		blockItem.setTitle("კორპუსი");
		blockItem.setName("aaaaItem111111");
		blockItem.setWidth(80);

		appartItem = new TextItem();
		appartItem.setTitle("ბინა");
		appartItem.setName("appartItem1111");
		appartItem.setWidth(80);

		addrAddInfoItem = new TextItem();
		addrAddInfoItem.setTitle("დამატებითი ინფორმაცია");
		addrAddInfoItem.setName("addrAddInfoItem");
		addrAddInfoItem.setWidth(269);

		formAddressParams.setFields(headerItemAddrParams, oldAddItem,
				adressOpCloseItem, adressItem, blockItem, appartItem,
				addrAddInfoItem);

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

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

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

		hLayoutItem.setMembers(saveItem, cancItem);

		HTMLFlow htmlFlow = new HTMLFlow();
		htmlFlow.setWidth100();
		htmlFlow.setHeight(10);
		String contents = "<hr style=\"border: 1px solid #9aaaba;\"></hr>";
		htmlFlow.setContents(contents);
		htmlFlow.setStyleName("paddingLeft12");

		HTMLFlow htmlFlow1 = new HTMLFlow();
		htmlFlow1.setHeight(10);
		htmlFlow1.setWidth100();
		htmlFlow1.setContents(contents);
		htmlFlow1.setStyleName("paddingLeft12");

		HTMLFlow htmlFlow2 = new HTMLFlow();
		htmlFlow2.setHeight(10);
		htmlFlow2.setWidth100();
		htmlFlow2.setContents(contents);
		htmlFlow2.setStyleName("paddingLeft12");

		VLayout tableLayout = new VLayout(5);
		tableLayout.setWidth100();
		tableLayout.setStyleName("paddingLeft12");

		HLayout buttons = new HLayout(5);

		IButton addPhone = new IButton("დამატება");
		addPhone.setIcon("new.png");

		addPhone.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				DlgAddEditAbPhone addEditAbPhone = new DlgAddEditAbPhone(null,
						listGridPhones);
				addEditAbPhone.show();
			}
		});

		IButton editPhone = new IButton("შესწორება");
		editPhone.setIcon("edit.png");

		editPhone.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {

				ListGridRecord listGridRecord = listGridPhones
						.getSelectedRecord();
				if (listGridRecord == null) {
					SC.say("მონიშნეთ ჩანაწერი ცხრილში!");
					return;
				}
				DlgAddEditAbPhone addEditAbPhone = new DlgAddEditAbPhone(
						listGridRecord, listGridPhones);
				addEditAbPhone.show();
			}
		});

		IButton deletePhone = new IButton("წაშლა");
		deletePhone.setIcon("delete.png");

		deletePhone.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				final ListGridRecord listGridRecord = listGridPhones
						.getSelectedRecord();
				if (listGridRecord == null) {
					SC.say("მონიშნეთ ჩანაწერი ცხრილში!");
					return;
				}

				SC.ask("დარწმუნებული ხართ რომ გნებავთ ჩანაწერის წაშლა ? ",
						new BooleanCallback() {
							@Override
							public void execute(Boolean value) {
								if (value) {
									abPhonesClientDS.removeData(listGridRecord);
								}
							}
						});
			}
		});

		buttons.setMembers(addPhone, editPhone, deletePhone);
		tableLayout.setMembers(listGridPhones, buttons);

		hLayout.setMembers(formPersInfo, htmlFlow, tableLayout, htmlFlow1,
				formAddress, htmlFlow2, formAddressParams, hLayoutItem);

		addItem(hLayout);

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

		saveItem.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {

			}
		});
		fillCombos();

		citiesItem.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				Object value = citiesItem.getValue();
				if (value == null) {
					return;
				}
				Integer city_id = null;
				try {
					city_id = Integer.parseInt(value.toString());
				} catch (NumberFormatException e) {
					return;
				}
				fillStreetsCombo(city_id);
				fillCityRegionCombo(city_id);
			}
		});
		streetItem.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				ListGridRecord record = streetItem.getSelectedRecord();
				if (record == null) {
					return;
				}
				String descr = record.getAttribute("street_location_geo");
				if (descr == null) {
					descr = "";
				}
				streetDescrItem.setValue(descr);
				Object cityRegId = record.getAttribute("city_region_id");
				Object cityId = record.getAttribute("city_id");
				if (cityRegId != null && cityId != null) {
					try {
						Integer iCityRegId = Integer.parseInt(cityRegId
								.toString());
						Integer iCityId = Integer.parseInt(cityId.toString());
						fillCityRegionCombo(iCityId);
						regionItem.setValue(iCityRegId);
					} catch (NumberFormatException e) {
						SC.say(e.toString());
						return;
					}
				}
			}
		});
		streetItem.addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				Object value = citiesItem.getValue();
				if (value == null) {
					return;
				}
				Integer city_id = null;
				try {
					city_id = Integer.parseInt(value.toString());
				} catch (NumberFormatException e) {
					return;
				}
				fillStreetsCombo(city_id);
			}
		});
		regionItem.addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				Object value = citiesItem.getValue();
				if (value == null) {
					return;
				}
				Integer city_id = null;
				try {
					city_id = Integer.parseInt(value.toString());
				} catch (NumberFormatException e) {
					return;
				}
				fillCityRegionCombo(city_id);
			}
		});

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

	}

	private void fillCombos() {
		try {
			DataSource firstNamesDS = DataSource.get("FirstNameDS");
			if (firstNamesDS != null) {
				firstNameItem.setOptionOperationId("firstNameSearch");
				firstNameItem.setOptionDataSource(firstNamesDS);
				firstNameItem.setValueField("firstname_Id");
				firstNameItem.setDisplayField("firstname");
			}
		} catch (Exception e) {
			SC.say(e.toString());
		}
		try {
			DataSource lastNamesDS = DataSource.get("LastNameDS");
			if (lastNamesDS != null) {
				lastNameItem.setOptionOperationId("lastNameSearch");
				lastNameItem.setOptionDataSource(lastNamesDS);
				lastNameItem.setValueField("lastname_Id");
				lastNameItem.setDisplayField("lastname");
			}
		} catch (Exception e) {
			SC.say(e.toString());
		}
		try {
			DataSource citiesDS = DataSource.get("CitiesDS");
			if (citiesDS != null) {
				Integer defCityTbilisiId = 2208;
				citiesItem.setOptionOperationId("customCitiesSearch");
				citiesItem.setOptionDataSource(citiesDS);
				citiesItem.setValueField("city_id");
				citiesItem.setDisplayField("city_name_geo");
				citiesItem.setValue(defCityTbilisiId);
				fillStreetsCombo(defCityTbilisiId);
			}
		} catch (Exception e) {
			SC.say(e.toString());
		}
	}

	private void fillStreetsCombo(Integer city_id) {
		try {
			DataSource streetsDS = DataSource.get("StreetsDS");
			if (streetsDS != null) {
				Criterion criterion = new Criterion();
				criterion.setAttribute("city_id", city_id);
				streetItem.setOptionCriteria(criterion);
				streetItem.setOptionOperationId("customStreetsSearch");
				streetItem.setOptionDataSource(streetsDS);
				streetItem.setValueField("street_district_id");
				streetItem.setDisplayField("street_name_geo");
			}
		} catch (Exception e) {
			SC.say(e.toString());
		}
	}

	private void fillCityRegionCombo(Integer city_id) {
		try {
			DataSource streetsDS = DataSource.get("CityRegionDS");
			if (streetsDS != null) {
				Criterion criterion = new Criterion();
				criterion.setAttribute("city_id", city_id);
				regionItem.setOptionCriteria(criterion);
				regionItem.setOptionOperationId("customCityRegionSearch");
				regionItem.setOptionDataSource(streetsDS);
				regionItem.setValueField("city_region_id");
				regionItem.setDisplayField("city_region_name_geo");
			}
		} catch (Exception e) {
			SC.say(e.toString());
		}
	}

	private void saveAbonentsData(Abonent abonent) {
		try {
			ListGridRecord nameRecord = firstNameItem.getSelectedRecord();
			if (nameRecord == null
					|| nameRecord.getAttributeAsInt("firstname_Id") == null) {
				SC.say("გთხოვთ აირჩიოთ სახელი !");
				return;
			}
			ListGridRecord lastNameRecord = lastNameItem.getSelectedRecord();
			if (lastNameRecord == null
					|| lastNameRecord.getAttributeAsInt("lastname_Id") == null) {
				SC.say("გთხოვთ აირჩიოთ გვარი !");
				return;
			}

			ListGridRecord cityRecord = citiesItem.getSelectedRecord();
			if (cityRecord == null
					|| cityRecord.getAttributeAsInt("city_id") == null) {
				SC.say("გთხოვთ აირჩიოთ ქალაქი !");
				return;
			}

			ListGridRecord streetRecord = streetItem.getSelectedRecord();
			if (streetRecord == null
					|| streetRecord.getAttributeAsInt("street_district_id") == null) {
				SC.say("გთხოვთ აირჩიოთ ქუჩა !");
				return;
			}

			ListGridRecord cityRegionRecord = regionItem.getSelectedRecord();
			if (cityRegionRecord == null
					|| cityRegionRecord.getAttributeAsInt("city_region_id") == null) {
				SC.say("გთხოვთ აირჩიოთ უბანი !");
				return;
			}

			Object addrStatType = adressOpCloseItem.getValue();
			if (addrStatType == null) {
				SC.say("გთხოვთ აირჩიოთ მისამართი ღიაა თუ დაფარული !");
				return;
			}
			Integer iAddrStatType = null;
			try {
				iAddrStatType = Integer.parseInt(addrStatType.toString());
			} catch (NumberFormatException e) {
				SC.say("გთხოვთ აირჩიოთ მისამართი ღიაა თუ დაფარული !");
				return;
			}
			Object address = adressItem.getValue();
			String sAddress = "";
			if (address != null) {
				sAddress = address.toString();
			}

			Object block = blockItem.getValue();
			String sBlock = "";
			if (block != null) {
				sBlock = block.toString();
			}

			Object appart = appartItem.getValue();
			String sAppart = "";
			if (appart != null) {
				sAppart = appart.toString();
			}

			Object addrAddInfo = addrAddInfoItem.getValue();
			String sAddrAddInfo = "";
			if (addrAddInfo != null) {
				sAddrAddInfo = addrAddInfo.toString();
			}
			ListGridRecord phoneRecors[] = listGridPhones.getRecords();
			if (phoneRecors == null || phoneRecors.length <= 0) {
				SC.say("გთხოვთ შეიყვანოთ მინიმუმ 1 ნომერი !");
				return;
			}

			List listPhones = new LinkedList();
			Map mapPhoneProps = new LinkedHashMap();
			for (ListGridRecord listGridRecord : phoneRecors) {
				
				mapPhoneProps.put("deleted", 0);
				mapPhoneProps.put("is_hide",
						listGridRecord.getAttributeAsInt("is_hide"));
				mapPhoneProps.put("is_hide_descr",
						listGridRecord.getAttribute("is_hide_descr"));
				mapPhoneProps.put("is_parallel",
						listGridRecord.getAttributeAsInt("is_parallel"));
				mapPhoneProps.put("is_parallel_descr",
						listGridRecord.getAttribute("is_parallel_descr"));
				mapPhoneProps
						.put("phone", listGridRecord.getAttribute("phone"));
				mapPhoneProps.put("phone_state",
						listGridRecord.getAttribute("phone_state"));
				mapPhoneProps.put("phone_state_id",
						listGridRecord.getAttributeAsInt("phone_state_id"));
				mapPhoneProps.put("phone_status",
						listGridRecord.getAttribute("phone_status"));
				mapPhoneProps.put("phone_status_id",
						listGridRecord.getAttribute("phone_status_id"));
				mapPhoneProps.put("phone_type",
						listGridRecord.getAttribute("phone_type"));
				mapPhoneProps.put("phone_type",
						listGridRecord.getAttributeAsInt("phone_type_id"));
				listPhones.add(mapPhoneProps);
			}
			
			com.smartgwt.client.rpc.RPCManager.startQueue();
			Record record = new Record();
			record.setAttribute("listPhones", mapPhoneProps);
			record.setAttribute("firstname_id",
					nameRecord.getAttributeAsInt("firstname_Id"));
			record.setAttribute("lastname_id",
					lastNameRecord.getAttributeAsInt("lastname_Id"));
			record.setAttribute("city_id",
					cityRecord.getAttributeAsInt("city_id"));
			record.setAttribute("street_id",
					streetRecord.getAttributeAsInt("street_id"));
			record.setAttribute("city_region_id",
					cityRegionRecord.getAttributeAsInt("city_region_id"));

			record.setAttribute("address_hide", iAddrStatType);
			record.setAttribute("addr_number", sAddress);
			record.setAttribute("addr_block", sBlock);
			record.setAttribute("addr_appt", sAppart);
			record.setAttribute("addr_descr", sAddrAddInfo);
			record.setAttribute("loggedUserName",
					CallCenter.sessionPerson.getUserName());

			DSRequest req = new DSRequest();
			req.setAttribute("operationId", "addOrUpdateAbonent");

			abonentsDS.addData(record, new DSCallback() {
				@Override
				public void execute(DSResponse response, Object rawData,
						DSRequest request) {
					destroy();
				}
			}, req);
			com.smartgwt.client.rpc.RPCManager.sendQueue();

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