@SuppressWarnings("serial")
@Widgetset("com.fau.amos.team2.WoundManagement.widgetset.WoundManagementWidgetset")
@Theme("wm-responsive")
@PreserveOnRefresh
public class WoundManagementUI extends UI {
	
	private OfflineModeExtension offlineModeSettings;

	private WrappedSession session;
		
	public WrappedSession getMySession() {
		return session;
	}
	
	public Environment getEnvironment() {
		return (Environment)session.getAttribute("e");
	}
	
	private void initializeEnvironment(VaadinRequest request) {
		session = request.getWrappedSession(true);
		
		if (session.getAttribute("e") == null) {
			session.setAttribute("e", new Environment());
			
			System.out.println("Created new environment for session " + session.getId());
		}
		else {
			System.out.println("Resumed existing environment for session " + session.getId());
		}
	}
	
	
	@Override
	protected void init(VaadinRequest request) {	

		initializeEnvironment(request);
		
		getEnvironment().setCurrentUriFragment("login");
		getPage().setUriFragment(getEnvironment().getCurrentUriFragment());
		
		getPage().addUriFragmentChangedListener(
	               new UriFragmentChangedListener() {
	           public void uriFragmentChanged(
	                   UriFragmentChangedEvent source) {
	               enter(source.getUriFragment());
	            }
	        });

	        // Read the initial URI fragment
	        enter(getPage().getUriFragment());
	}

	private void setLocale() {
		Locale currentLocale = Page.getCurrent().getWebBrowser().getLocale();
		System.out.println("Current locale browser: " + currentLocale.getLanguage());
		getEnvironment().setCurrentLocale(currentLocale);
		MessageResources.setLocale(getEnvironment().getCurrentLocale());
	}
	
	public void goOffline() {
		// TODO: Check if needed
		offlineModeSettings.goOffline();
	}

	private void enableOfflineMode() {
		offlineModeSettings = new OfflineModeExtension();
		offlineModeSettings.extend(this);
		offlineModeSettings.setPersistentSessionCookie(true);
		offlineModeSettings.setOfflineModeEnabled(true);
	}
	
	public void enter(String uriFragment){
		if (uriFragment != null){
			switch (uriFragment){
			case "login":
				enableOfflineMode();
				setLocale();
				setImmediate(true);
				if (getEnvironment().getCurrentEmployee() == null){
					setContent(new UserLoginView());
				} else {
					getEnvironment().setCurrentUriFragment("patientSelection");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				getPage().setTitle("Wound Management Session " + session.getId());
				break;
			case "patientSelection":
				if (getEnvironment().getCurrentEmployee() != null){
					setContent(new PatientSelectionView());
				} else {
					getEnvironment().setCurrentUriFragment("login");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				break;
			case "patient":
				if (getEnvironment().getCurrentEmployee() != null){
					if (getEnvironment().getCurrentPatient() != null){
						setContent(new PatientView());
					} else  {
						getEnvironment().setCurrentUriFragment("patient");
						Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
					}
				} else {
					getEnvironment().setCurrentUriFragment("login");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				break;
			case "woundDescriptions":
				if (getEnvironment().getCurrentEmployee() != null){
					if (getEnvironment().getCurrentWound() != null){
						setContent(new WoundDescriptionListView());
					} else {
						if (getEnvironment().getCurrentPatient() != null){
							getEnvironment().setCurrentUriFragment("patient");
							Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
						} else {
							getEnvironment().setCurrentUriFragment("patientSelection");
							Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
						}
					}
				} else {
					getEnvironment().setCurrentUriFragment("login");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				break;
			case "createWoundDescription":
				if (getEnvironment().getCurrentEmployee() != null){
					if (getEnvironment().getCurrentWound() != null){
						setContent(new CreateWoundDescriptionView());
					} else {
						if (getEnvironment().getCurrentPatient() != null){
							getEnvironment().setCurrentUriFragment("patient");
							Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
						} else {
							getEnvironment().setCurrentUriFragment("patientSelection");
							Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
						}
					}
				} else {
					getEnvironment().setCurrentUriFragment("login");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				break;
			case "showWoundDescription":
				if (getEnvironment().getCurrentEmployee() != null){
					if (getEnvironment().getCurrentWoundDescription() != null){
						setContent(new ShowWoundDescriptionView());
					} else {
						if (getEnvironment().getCurrentWound() != null){
							getEnvironment().setCurrentUriFragment("woundDescriptions");
							Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
						} else {
							if (getEnvironment().getCurrentPatient() != null){
								getEnvironment().setCurrentUriFragment("patient");
								Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
							} else {
								getEnvironment().setCurrentUriFragment("patientSelection");
								Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
							}
						}
					}
				} else {
					getEnvironment().setCurrentUriFragment("login");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				break;
			case "showPhoto":
				if (getEnvironment().getCurrentEmployee() != null){
					if (getEnvironment().getCurrentWoundDescription() != null){
						setContent(new ShowWoundPhotoView());
					} else {
						if (getEnvironment().getCurrentWound() != null){
							getEnvironment().setCurrentUriFragment("woundDescriptions");
							Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
						} else {
							if (getEnvironment().getCurrentPatient() != null){
								getEnvironment().setCurrentUriFragment("patient");
								Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
							} else {
								getEnvironment().setCurrentUriFragment("patientSelection");
								Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
							}
						}
					}
				} else {
					getEnvironment().setCurrentUriFragment("login");
					Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
				}
				break;
			}

		}
		
	}
} public enum BodyLocation {
	
	NULL(0),
	HINTERKOPF(1),
	SCHAEDELANSATZ(2),
	NACKEN(3),
	SCHULTERBLATT_OBEN_LI(4),
	SCHULTERBLATT_UNTEN_LI(5),
	SCHULTERBLATT_OBEN_RE(6),
	SCHULTERBLATT_UNTEN_RE(7),
	ELLENBOGEN_LI(8),
	ELLENBOGEN_RE(9),
	KREUZBEIN(10),
	FERSE_LI(11),
	FERSE_RE(12),
	GESAESS_LI(13),
	GESAESS_RE(14),
	WADE_LI(15),
	WADE_RE(16),
	WIRBELSAEULE(17),
	ANALFALTE(18),
	HAND_AUSSEN_LI(19),
	HAND_AUSSEN_RE(20),
	
	OHR_RE(21),
	SCHULTER_RE(22),
	TROCHANTER_RE(23),
	KNOECHEL_RE(24),
	UNTERE_FERSE_RE(25),
	UNTERE_SOHLE_RE(26),
	ZEHENUNTERSEITE_RE(27),
	ZEHENOBERSEITE_RE(28),
	FUSSOBERSEITE_RE(29),
	OBERARM_RE(30),
	UNTERARM_RE(31),
	
	OHR_LI(41),
	SCHULTER_LI(42),
	TROCHANTER_LI(43),
	KNOECHEL_LI(44),
	UNTERE_FERSE_LI(45),
	UNTERE_SOHLE_LI(46),
	ZEHENUNTERSEITE_LI(47),
	ZEHENOBERSEITE_LI(48),
	FUSSOBERSEITE_LI(49),
	OBERARM_LI(50),
	UNTERARM_LI(51),

	GESICHT(61),
	KNIE_RE(62),
	KNIE_LI(63),
	BRUSTBEIN(64),
	BRUST_RE(65),
	BRUST_LI(66),
	BAUCH(67),
	LEISTE_RE(68),
	LEISTE_LI(69),
	HAND_RE(70),
	HAND_LI(71),
	SCHIENBEIN_RE(72),
	SCHIENBEIN_LI(73),
	OBERSCHENKEL_RE(74),
	OBERSCHENKEL_LI(75),
	RIPPENBOGEN_RE(76),
	RIPPENBOGEN_LI(77)
	;
	
	private final int value;
	
	private BodyLocation (int i){
		this.value = i;
	}
	
	private static Map<Integer, BodyLocation> map = new HashMap<Integer, BodyLocation>();

    static {
        for (BodyLocation locationEnum : BodyLocation.values()) {
            map.put(locationEnum.value, locationEnum);
        }
    }
    
    public static BodyLocation valueOf(int locationNo) {
        return map.get(locationNo);
    }
	
	public String toString(){
		switch (this){
		case NULL: return "-";
		case HINTERKOPF: return "Hinterkopf";
		case SCHAEDELANSATZ: return "Schädelansatz";
		case NACKEN: return "Nacken";
		case SCHULTERBLATT_OBEN_LI: return "Schulterblatt oben links";
		case SCHULTERBLATT_UNTEN_LI: return "Schulterblatt unten links";
		case SCHULTERBLATT_OBEN_RE: return "Schulterblatt oben rechts";
		case SCHULTERBLATT_UNTEN_RE: return "Schulterblatt unten rechts";
		case ELLENBOGEN_LI: return "Ellenbogen links";
		case ELLENBOGEN_RE: return "Ellenbogen rechts";
		case KREUZBEIN: return "Kreuzbein";
		case FERSE_LI: return "Ferse links";
		case FERSE_RE: return "Ferse rechts";
		case GESAESS_LI: return "Gesäß links";
		case GESAESS_RE: return "Gesäß rechts";
		case WADE_LI: return "Wade links";
		case WADE_RE: return "Wade rechts";
		case WIRBELSAEULE: return "Wirbelsäule";
		case ANALFALTE: return "Analfalte";
		case HAND_AUSSEN_LI: return "Hand außen links";
		case HAND_AUSSEN_RE: return "Hand außen rechts";
		
		case OHR_RE: return "Ohr rechts";
		case SCHULTER_RE: return "Schulter rechts";
		case TROCHANTER_RE: return "Trochanter rechts";
		case KNOECHEL_RE: return "Knöchel rechts";
		case UNTERE_FERSE_RE: return "Untere Ferse rechts";
		case UNTERE_SOHLE_RE: return "Untere Sohle rechts";
		case ZEHENUNTERSEITE_RE: return "Zehenunterseite rechts";
		case ZEHENOBERSEITE_RE: return "Zehenoberseite rechts";
		case FUSSOBERSEITE_RE: return "Fußoberseite rechts";
		case OBERARM_RE: return "Oberarm rechts";
		case UNTERARM_RE: return "Unterarm rechts";
		
		case OHR_LI: return "Ohr links";
		case SCHULTER_LI: return "Schulter links";
		case TROCHANTER_LI: return "Trochanter links";
		case KNOECHEL_LI: return "Knöchel links";
		case UNTERE_FERSE_LI: return "Untere Ferse links";
		case UNTERE_SOHLE_LI: return "Untere Sohle links";
		case ZEHENUNTERSEITE_LI: return "Zehenunterseite links";
		case ZEHENOBERSEITE_LI: return "Zehenoberseite links";
		case FUSSOBERSEITE_LI: return "Fußoberseite links";
		case OBERARM_LI: return "Oberarm links";
		case UNTERARM_LI: return "Unterarm links";

		case GESICHT: return "Gesicht";
		case KNIE_RE: return "Knie rechts";
		case KNIE_LI: return "Knie links";
		case BRUSTBEIN: return "Brustbein";
		case BRUST_RE: return "Brust rechts";
		case BRUST_LI: return "Brust links";
		case BAUCH: return "Bauch";
		case LEISTE_RE: return "Leiste rechts";
		case LEISTE_LI: return "Leiste links";
		case HAND_RE: return "Hand rechts";
		case HAND_LI: return "Hand links";
		case SCHIENBEIN_RE: return "Schienbein rechts";
		case SCHIENBEIN_LI: return "Schienbein links";
		case OBERSCHENKEL_RE: return "Oberschenkel rechts";
		case OBERSCHENKEL_LI: return "Oberschenkel links";
		case RIPPENBOGEN_RE: return "Rippenbogen rechts";
		case RIPPENBOGEN_LI: return "Rippenbogen links";
		}
		return "";
	}
	
	public String toFullString(){
		if (this == NULL){
			return this.toString();
		} 
		return this.value + " - " + this.toString();
	}
	
	public int getValue(){
		return this.value;
	}

} public enum Origination {

	NULL(0),
	HAEUSLICH(1),
	KRANKENHAUS_EINZUG(2),
	ANDERE_EINRICHTUNG(3),
	KRANKENHAUS_RUECKKEHR(4), 
	SONSTIGE_VOR_HEIMAUFENTHALT(5), 
	EIGENE_EINRICHTUNG(6), 
	URLAUB(7), 
	AMBULANTE_OP(8), 
	SONSTIGE_WAEHREND_HEIMAUFENTHALT(9);
	
	private final int value;
	
	private Origination(int i){
		this.value = i;
	}
	
	private static Map<Integer, Origination> map = new HashMap<Integer, Origination>();

    static {
        for (Origination originationEnum : Origination.values()) {
            map.put(originationEnum.value, originationEnum);
        }
    }
    
    public static Origination valueOf(int originationNo) {
        return map.get(originationNo);
    }
	
	public String toString(){
		switch (this){
		case NULL: return "";
		case HAEUSLICH: return "Häuslich";
		case KRANKENHAUS_EINZUG: return "Krankenhaus/Einzug";
		case ANDERE_EINRICHTUNG: return "Andere Einrichtung";
		case KRANKENHAUS_RUECKKEHR: return "Krankenhaus/Rückkehr";
		case SONSTIGE_VOR_HEIMAUFENTHALT: return "Sonstige vor Heimaufenthalt";
		case EIGENE_EINRICHTUNG: return "Eigene Einrichtung";
		case URLAUB: return "Urlaub";
		case AMBULANTE_OP: return "Ambulante OP";
		case SONSTIGE_WAEHREND_HEIMAUFENTHALT: return "Sonstige während Heimaufenthalt";
		}
		return "";
	}
	
	public String toFullString(){
		if (this == NULL){
			return this.toString();
		}
		return this.value + " - " + this.toString();
	}
	
	public int getValue(){
		return this.value;
	}
} @SuppressWarnings("serial")
@Entity
@Table(name = "BEWOPE07")
@NamedQueries({
		@NamedQuery(name = "Patient.findAll", query = "SELECT p FROM Patient p"),
		@NamedQuery(name = "Patient.deleteAll", query = "DELETE FROM Patient") })
public class Patient implements BusinessObject {
	@Id
	@Column(name = "NR", nullable = false)
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	private int id;

	@Column(name = "KENMDT07_NR", nullable = false)
	private int sensoID;

	@Column(name = "NAME", length = 35)
	private String lastName;

	@Column(name = "VORNAME", length = 35)
	private String firstName;

	@Column(name = "GESCHLECHT", length = 100)
	private String gender;

	@Column(name = "TITEL", length = 100)
	private String title;

	@Column(name = "ANREDE", length = 100)
	private String salutation;

	@Column(name = "GEBDATUM")
	private Date birthday;

	@Column(name = "ZIMMER", length = 8)
	private String room;

	@ManyToOne
	@JoinColumn(name = "STATIONEN07_NR", referencedColumnName = "NR")
	private Ward ward;

	@OneToMany(targetEntity = Wound.class, mappedBy = "patient")
	private List<Wound> wounds;

	@Column(name = "SUCHBEZ", length = 35)
	private String keyword;

	@Column(name = "EINZUG")
	private Date entryDate;

	@Column(name = "UNTERBRINGUNG", length = 1)
	private String accomodation;

	// Standard constructor is setting the sensoID to default value
	public Patient() {
		this.sensoID = 1;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getSensoID() {
		return sensoID;
	}

	public void setSensoID(int sensoID) {
		this.sensoID = sensoID;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getGender() {
		return gender;
	}

	public Sex getSex() {
		if (getGender() != null && getGender().length() > 0)
			return Sex.valueOf(getGender().charAt(0));
		
		return Sex.NEUTER;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getSalutation() {
		return salutation;
	}

	public void setSalutation(String salutation) {
		this.salutation = salutation;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getRoom() {
		return room;
	}

	public void setRoom(String room) {
		this.room = room;
	}

	public Ward getWard() {
		return ward;
	}

	public void setWard(Ward ward) {
		this.ward = ward;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public Date getEntryDate() {
		return entryDate;
	}

	public void setEntryDate(Date entryDate) {
		this.entryDate = entryDate;
	}

	public AccomodationType getAccomodation() {
		return AccomodationType.valueOf(accomodation);
	}

	public void setAccomodation(AccomodationType accomodation) {
		this.accomodation = accomodation.toString();
	}

	public List<Wound> getWounds() {
		// TODO: this is just a workaround! shall not call database every time a patients wounds are needed.
		return WoundProvider.getInstance().getAllForPatient(this);
	}

	public List<Wound> getCurrentWounds() {
		// TODO: this is just a workaround! shall not call database every time a patients wounds are needed.
		return WoundProvider.getInstance().getCurrentForPatient(this);
	}
} @SuppressWarnings("serial")
@Entity
@Table(name = "BEWDKL07")
@NamedQueries({
		@NamedQuery(name = "Wound.currentForPatient", query = "SELECT w FROM Wound w WHERE w.patient=:patient AND w.endDate IS NULL"),
		@NamedQuery(name = "Wound.deleteAll", query = "DELETE FROM Wound"),
		@NamedQuery(name = "Wound.getMaxDecubitusId", query = "SELECT MAX(w.decubitusId) FROM Wound w"),
		@NamedQuery(name = "Wound.allForPatient", query = "SELECT w FROM Wound w WHERE w.patient=:patient") })
public class Wound implements BusinessObject {
	@Id
	@Column(name = "NR", nullable = false)
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	private int id;

	@Column(name = "KENMDT07_NR", nullable = false)
	private int sensoID;

	@ManyToOne
	@JoinColumn(name = "BEWOPE07_NR", nullable = false, referencedColumnName = "NR")
	private Patient patient;
	
	@Column(name = "ERFASSUNGSDATUM", nullable = false)
	private Date recordingDate;

	@ManyToOne
	@JoinColumn(name = "MITAPE07_NR", nullable = false, referencedColumnName = "NR")
	private Employee recordingEmployee;
	
	@Column(name = "ENDEDATUM")
	private Date endDate;

	@ManyToOne
	@JoinColumn(name = "ENDE_MITAPE07_NR", referencedColumnName = "NR")
	private Employee cureEmployee;
	
	@Column(name = "KOERPERSTELLE", length=200)
	private String bodyLocation;

	@Column(name = "KOERPERSTELLE_CODE", nullable = false)
	private int bodyLocationCode;

	@Column(name = "GROESSE1")
	private int size1;

	@Column(name = "GROESSE2")
	private int size2;

	@Column(name = "TIEFE")
	private int depth;

	@Column(name = "BEMERKUNG", length=2000)
	private String description;

	@Column(name = "ENTSTEHUNG")
	private int origination;

	@ManyToOne
	@JoinColumn(name = "KENWUN07_NR", referencedColumnName = "NR")
	private WoundType woundType;

	@ManyToOne
	@JoinColumn(name = "KENDEK07_NR", referencedColumnName = "NR")
	private WoundLevel woundLevel;

	@Column(name = "DEKUBITUSNR")
	private int decubitusId;

	@OneToMany(targetEntity = WoundDescription.class, mappedBy = "wound")
	private List<WoundDescription> wounddescriptions;

	public Wound() {
		this.sensoID = 1;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getSensoID() {
		return sensoID;
	}

	public void setSensoID(int sensoID) {
		this.sensoID = sensoID;
	}

	public Patient getPatient() {
		return patient;
	}

	public void setPatient(Patient patient) {
		this.patient = patient;
	}

	public Date getRecordingDate() {
		return recordingDate;
	}

	public void setRecordingDate(Date recordingDate) {
		this.recordingDate = recordingDate;
	}

	public Employee getRecordingEmployee() {
		return recordingEmployee;
	}

	public void setRecordingEmployee(Employee recordingEmployee) {
		this.recordingEmployee = recordingEmployee;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	@SuppressWarnings("deprecation")
	public void setEndDate(int year, int month, int day) {
		this.endDate = new Date(year, month, day);
	}

	public Employee getCureEmployee() {
		return cureEmployee;
	}

	public void setCureEmployee(Employee cureEmployee) {
		this.cureEmployee = cureEmployee;
	}

	public String getBodyLocation() {
		return bodyLocation;
	}

	public void setBodyLocation(String bodyLocation) {
		this.bodyLocation = bodyLocation;
	}

	public int getBodyLocationCode() {
		return bodyLocationCode;
	}

	public void setBodyLocationCode(int bodyLocationCode) {
		this.bodyLocationCode = bodyLocationCode;
	}

	public int getSize1() {
		return size1;
	}

	public void setSize1(int size1) {
		this.size1 = size1;
	}

	public int getSize2() {
		return size2;
	}

	public void setSize2(int size2) {
		this.size2 = size2;
	}

	public int getDepth() {
		return depth;
	}

	public void setDepth(int depth) {
		this.depth = depth;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public int getOrigination() {
		return origination;
	}

	public void setOrigination(int origination) {
		this.origination = origination;
	}

	public WoundLevel getWoundLevel() {
		return woundLevel;
	}

	public void setWoundLevel(WoundLevel woundLevel) {
		this.woundLevel = woundLevel;
	}

	public WoundType getWoundType() {
		return woundType;
	}

	public void setWoundType(WoundType woundType) {
		this.woundType = woundType;
	}

	public int getDecubitusId() {
		return decubitusId;
	}

	public void setDecubitusId(int decubitusId) {
		this.decubitusId = decubitusId;
	}

	public List<WoundDescription> getWoundDescriptions() {
		// TODO: this is just a workaround! shall not call database every time a wounds wounddescriptions are needed.
		return WoundDescriptionProvider.getInstance().getAllForWound(this);
	}

	
} @SuppressWarnings("serial")
@Entity
@Table(name = "KENDEK07")
@NamedQueries({
	@NamedQuery(name="WoundLevel.deleteAll", query="DELETE FROM WoundLevel"),
	@NamedQuery(name="WoundLevel.allForWoundType", query = "SELECT w FROM WoundLevel w WHERE w.woundType=:woundType")
})
public class WoundLevel implements BusinessObject {
	@Id
	@Column(name = "NR", nullable = false)
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	private int id;
	
	@Column(name = "KENMDT07_NR", nullable = false)
	private int sensoID;
	
	@Column(name = "BEZEICH", nullable = false, length=2000)
	private String characterisation;
	
	@Column(name = "GRAD", nullable = false)
	private int level;
	
	@ManyToOne
	@JoinColumn(name = "KENWUN07_NR", nullable = false, referencedColumnName = "NR")
	private WoundType woundType;
	
	@Column(name = "BESCHREIB", length=4000)
	private String description;
	
	@Column(name = "KUERZL", nullable = false, length=5)
	private String abbreviation;
	
	@Column(name = "POS")
	private int position;
	
	public WoundLevel() { 
		this.sensoID=1;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getPos() {
		return this.position;
	}
	
	public void setPos(int pos) {
		this.position = pos;
	}

	public int getSensoID() {
		return sensoID;
	}

	public void setSensoID(int sensoID) {
		this.sensoID = sensoID;
	}

	public String getCharacterisation() {
		return characterisation;
	}

	public void setCharacterisation(String characterisation) {
		this.characterisation = characterisation;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public WoundType getWoundType() {
		return woundType;
	}

	public void setWoundType(WoundType woundType) {
		this.woundType = woundType;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getAbbreviation() {
		return abbreviation;
	}

	public void setAbbreviation(String abbreviation) {
		this.abbreviation = abbreviation;
	}
} public enum WoundLevelState {
	REQUIRED('p'),
	OPTIONAL('e'),
	FORBIDDEN('v');
	
	private char character;
	
	private WoundLevelState(char character) {
		this.character = character;
	}
	
	public String toString() {
		return Character.toString(this.character);
	}
	
	public static WoundLevelState enumOf(char character) {
		for (WoundLevelState type : WoundLevelState.values())
			if (character == type.character)
				return type;
		
		return null;
	}
	
	public static WoundLevelState enumOf(String string) {
		if (string.length() > 0)
			return enumOf(string.toLowerCase().charAt(0));
		
		return null;
	}
} @SuppressWarnings("serial")
@Entity
@Table(name = "KENWUN07")
@NamedQueries({
	@NamedQuery(name="WoundType.deleteAll", query="DELETE FROM WoundType")
})
public class WoundType implements BusinessObject {
	@Id
	@Column(name = "NR", nullable = false)
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	private int id;
	
	@Column(name = "KENMDT07_NR", nullable = false)
	private int sensoID;
	
	@Column(name = "BEZEICH", nullable = false, length=30)
	private String classification;

	
	@Column(name = "TYP", nullable = false, length=1)
	private String type;
	
	@Column(name = "GROESSEPFL", nullable = false, length=1)
	private String sizeIsRequired;

	@Column(name = "GRADSTATUS", nullable = false, length=1)
	private String levelState;
	
	@Column(name = "KOERPERSTELLEPFL", nullable = false, length=1)
	private String isBodyLocationRequired;
	
	public WoundType() {
		this.sensoID=1;
		this.levelState= "E";
		this.isBodyLocationRequired = "n";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getSensoID() {
		return sensoID;
	}

	public void setSensoID(int sensoID) {
		this.sensoID = sensoID;
	}

	public String getClassification() {
		return classification;
	}

	public void setClassification(String classification) {
		this.classification = classification;
	}

	public WoundKind getType() {
		return WoundKind.enumOf(type);
	}

	public void setType(WoundKind type) {
		this.type = type.toString();
	}

	public boolean isSizeIsRequired() {
		return BooleanToStringConverter.convertBack(sizeIsRequired);
	}
		
	public void setSizeIsRequired(boolean sizeIsRequired) {
		this.sizeIsRequired = BooleanToStringConverter.convert(sizeIsRequired);
	}

	public WoundLevelState getLevelState() {
		return WoundLevelState.enumOf(levelState);
	}

	public void setLevelState(WoundLevelState level) {
		this.levelState = level.toString();
	}

	public boolean isBodyLocationRequired() {
		return BooleanToStringConverter.convertBack(isBodyLocationRequired);
	}

	public void setBodyLocationRequired(boolean isBodyLocationRequired) {
		this.isBodyLocationRequired = BooleanToStringConverter.convert(isBodyLocationRequired);
	}
} public class WoundLevelProvider extends ObjectProvider<WoundLevel> {

	private static WoundLevelProvider instance;
	
	public WoundLevelProvider(Class<WoundLevel> type) {
		super(type);
	}
	
	/**
	 * @return The instance of <code>WoundLevelProvider</code> 
	 * */
	public static WoundLevelProvider getInstance() {
		if(instance == null) {
			instance = new WoundLevelProvider(WoundLevel.class);
		}
		return instance;
	}
	
	public void deleteAll() {
		EntityManager em = container.getEntityProvider().getEntityManager();
		em.getTransaction().begin();
		em.createNamedQuery("WoundLevel.deleteAll").executeUpdate();
		em.getTransaction().commit();

	}
	
	public List<WoundLevel> getAllFoWoundType(WoundType woundType){
		EntityManager em = container.getEntityProvider().getEntityManager();
		TypedQuery<WoundLevel> query = em.createNamedQuery("WoundLevel.allForWoundType", WoundLevel.class);
		query.setParameter("woundType", woundType);
		List<WoundLevel> resultList = query.getResultList();
		return resultList;
	}
} public class WoundProvider extends ObjectProvider<Wound> {

	private static WoundProvider instance;
	
	public WoundProvider(Class<Wound> type) {
		super(type);
	}
	
	/**
	 * @return The instance of <code>WoundProvider</code> 
	 * */
	public static WoundProvider getInstance() {
		if(instance == null) {
			instance = new WoundProvider(Wound.class);
		}
		return instance;
	}
	
	public void deleteAll() {
		EntityManager em = container.getEntityProvider().getEntityManager();
		em.getTransaction().begin();
		em.createNamedQuery("Wound.deleteAll").executeUpdate();
		em.getTransaction().commit();
	}
	
	public void add(Wound object) {
		EntityManager em = container.getEntityProvider().getEntityManager();
		TypedQuery<Integer> decubitusQuery = em.createNamedQuery("Wound.getMaxDecubitusId", Integer.class);
		List<Integer> resultList = decubitusQuery.getResultList();
		
		int decubitusId = 0;
		if (resultList != null && !resultList.isEmpty()) {
			decubitusId = resultList.get(0) != null ? resultList.get(0) : 0;
		}
		
		decubitusId++;
		
		object.setDecubitusId(decubitusId);
		
		super.add(object);
	}
	
	public List<Wound> getAllForPatient(Patient patient) {
		EntityManager em = container.getEntityProvider().getEntityManager();
		TypedQuery<Wound> query = em.createNamedQuery("Wound.allForPatient", Wound.class);
		query.setParameter("patient", patient);
		List<Wound> resultList = query.getResultList();
		return resultList;
	}
	
	public List<Wound> getCurrentForPatient(Patient patient) {
		EntityManager em = container.getEntityProvider().getEntityManager();
		TypedQuery<Wound> query = em.createNamedQuery("Wound.currentForPatient", Wound.class);
		query.setParameter("patient", patient);
		List<Wound> resultList = query.getResultList();
		return resultList;
	}
} public class WoundTypeProvider extends ObjectProvider<WoundType> {

	private static WoundTypeProvider instance;
	
	public WoundTypeProvider(Class<WoundType> type) {
		super(type);
	}
	
	/**
	 * @return The instance of <code>WoundTypeProvider</code> 
	 * */
	public static WoundTypeProvider getInstance() {
		if(instance == null) {
			instance = new WoundTypeProvider(WoundType.class);
		}
		return instance;
	}
	
	public void deleteAll() {
		EntityManager em = container.getEntityProvider().getEntityManager();
		em.getTransaction().begin();
		em.createNamedQuery("WoundType.deleteAll").executeUpdate();
		em.getTransaction().commit();
	}
} public class MessageResources {
	private static ResourceBundle messages;
	private static Locale locale;
	
	private MessageResources() { }
	
	public static final String getString(String key) {
		return messages.getString(key);
	}
	
	public static final String[] getStringArray(String key) {
		return messages.getStringArray(key);
	}
	
	public static Locale getLocale() {
		return locale;
	}

	public static void setLocale(Locale locale) {
		MessageResources.locale = locale;
		reset();
	}

	private static void reset() {
		messages = ResourceBundle.getBundle("bundles.MessagesBundle", locale);
	}

} @PreserveOnRefresh
public class PatientView extends SessionedNavigationView implements SelectedWoundChangeListener {
	private static final long serialVersionUID = -572027045788648039L;
	
	private Patient currentPatient;
	private WoundManager woundManager;
	
	private boolean showCurrentWoundsOnly;
	
	VerticalLayout rightContent = new VerticalLayout();
	VerticalLayout rightContent2;
		
	@SuppressWarnings("serial")
	public PatientView() {
		
		getEnvironment().setCurrentWoundDescription(null);
		this.currentPatient = getEnvironment().getCurrentPatient();
		this.showCurrentWoundsOnly = getEnvironment().getShowCurrentWoundsOnly();
		
		UserBar userBar = new UserBar(this);
		
		setCaption(currentPatient.getFirstName() + " " + currentPatient.getLastName());

		final CheckBox showOnlyCurrentWoundsSwitch = new CheckBox(MessageResources.getString("showHealedWounds"));
		
		showOnlyCurrentWoundsSwitch.setValue(!getBoolShowCurrentWoundsOnly());
		showOnlyCurrentWoundsSwitch.addValueChangeListener(new ValueChangeListener() {
			@Override
			public void valueChange(ValueChangeEvent event) {
				boolean scwo = !showOnlyCurrentWoundsSwitch.getValue();
				setBoolShowCurrentWoundsOnly(scwo);
				getEnvironment().setShowCurrentWoundsOnly(scwo);
				Page.getCurrent().setUriFragment("");
//				getEnvironment().setCurrentUriFragment("patient");
				Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
			}
			
		});
		showOnlyCurrentWoundsSwitch.setImmediate(true);
		
		createWoundManager();
		
		Label spacing = new Label("");
		spacing.addStyleName("spacingLabel");
		
		final GridLayout content = new GridLayout(3, 4);
		content.addStyleName("grid");
		
		final VerticalLayout switchSpacePic = new VerticalLayout();
		switchSpacePic.addComponents(showOnlyCurrentWoundsSwitch, 
					spacing, woundManager.getWoundSelector());
		content.addComponent(switchSpacePic, 0, 1, 0, 3);
		
		int wdth = UI.getCurrent().getPage().getBrowserWindowWidth();  
		int hght = UI.getCurrent().getPage().getBrowserWindowHeight();
		
		if (wdth > hght) {
			content.addComponent(rightContent, 2, 2);
		}else{
			switchSpacePic.addComponent(rightContent);
		}
		
		Page.getCurrent().addBrowserWindowResizeListener(new Page.BrowserWindowResizeListener() {

			@Override
			public void browserWindowResized(BrowserWindowResizeEvent event) {
				int width = UI.getCurrent().getPage().getBrowserWindowWidth();  
				int height = UI.getCurrent().getPage().getBrowserWindowHeight();
				if (width > height) {
					switchSpacePic.removeComponent(rightContent);
					content.addComponent(rightContent, 2, 2);
					rightContent.addStyleName("patViewRightContent");
					new Responsive(rightContent);
				}else{
					content.removeComponent(rightContent);
					switchSpacePic.addComponent(rightContent);
					rightContent.addStyleName("patViewRightContent");
					new Responsive(rightContent);
				}
				
			}
		});

		new Responsive(switchSpacePic);
		new Responsive(content);
		
		Wound wound = getEnvironment().getCurrentWound();
		if (wound != null){
			if (wound.getCureEmployee() != null){
				if (!showCurrentWoundsOnly){
					this.prepareSelectedWound(wound);
				}
			} else {
				this.prepareSelectedWound(wound);
			}
		}
		
		BackButton backButton = new BackButton(MessageResources.getString("patientSelection"), "patientSelection");
		setLeftComponent(backButton);
		setRightComponent(userBar);
		setContent(content);
	}

	
	private void createWoundManager() {
		float heightFactor = (getEnvironment().getWindowHeight()-104)/513;
		float widthFactor = getEnvironment().getWindowWidth()/600;
		
		float scaleFactor = widthFactor < heightFactor ? widthFactor : heightFactor;

		if (scaleFactor < 1){
			woundManager = new WoundManager(currentPatient, getBoolShowCurrentWoundsOnly(), scaleFactor);
		} else {
			woundManager = new WoundManager(currentPatient, getBoolShowCurrentWoundsOnly(), 1);
		}
		
		woundManager.addSelectedWoundChangeListener(this);
	}

	@Override
	public void selectedWoundChanged(SelectedWoundChangeEvent event) {
		Wound selectedWound = event.getWound();
		rightContent.removeAllComponents();	
		getEnvironment().setCurrentWound(selectedWound);
		if (selectedWound != null) {
			rightContent.addComponent(new ExistingWound(this, selectedWound));
		}
		else if (event.getWoundPosition() != null) {
			rightContent.addComponent(new NewWound(this, currentPatient, event.getWoundPosition().getBodyLocation()));
		}
	}
	
	public void setSelectedWound(Wound wound) {
		if (wound != null && wound.getPatient().getId() == currentPatient.getId()) {
			woundManager.addWound(wound);
			woundManager.setSelectedWound(wound);
		}
		else {
			woundManager.setSelectedWound(null);
		}
	}
	
	public void prepareSelectedWound(Wound wound) {
		if (wound != null && wound.getPatient().getId() == currentPatient.getId()) {
			woundManager.addWound(wound);
			woundManager.setSelectedWound(wound);
		}
		else {
			woundManager.setSelectedWound(null);
		}
	}
	
	public Patient getPatient(){
		return currentPatient;
	}

	public boolean getBoolShowCurrentWoundsOnly() {
		return this.showCurrentWoundsOnly;
	}
	
	public void setBoolShowCurrentWoundsOnly(Boolean showCurrentWoundsOnly) {
		this.showCurrentWoundsOnly = showCurrentWoundsOnly;
	}

}
import java.util.Collection;
import java.util.Date;
import java.util.List;
import com.fau.amos.team2.WoundManagement.WoundManagementUI;
import com.fau.amos.team2.WoundManagement.model.BodyLocation;
import com.fau.amos.team2.WoundManagement.model.Origination;
import com.fau.amos.team2.WoundManagement.model.Patient;
import com.fau.amos.team2.WoundManagement.model.Wound;
import com.fau.amos.team2.WoundManagement.model.WoundLevel;
import com.fau.amos.team2.WoundManagement.model.WoundLevelState;
import com.fau.amos.team2.WoundManagement.model.WoundType;
import com.fau.amos.team2.WoundManagement.provider.WoundLevelProvider;
import com.fau.amos.team2.WoundManagement.provider.WoundProvider;
import com.fau.amos.team2.WoundManagement.provider.WoundTypeProvider;
import com.fau.amos.team2.WoundManagement.resources.MessageResources;
import com.fau.amos.team2.WoundManagement.ui.PatientView;
import com.vaadin.addon.touchkit.ui.DatePicker;
import com.vaadin.addon.touchkit.ui.NumberField;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
package com.fau.amos.team2.WoundManagement.ui.subviews;



@SuppressWarnings("serial")
public class NewWound extends FormLayout {

	private Patient currentPatient;
	
	private static WoundProvider woundProvider = 
			WoundProvider.getInstance();
	private static WoundTypeProvider woundTypeProvider = 
			WoundTypeProvider.getInstance();
	private static WoundLevelProvider woundLevelProvider = 
			WoundLevelProvider.getInstance();
	
	public NewWound(final PatientView parentView, final Patient patient, BodyLocation bodyLocation){
		currentPatient = patient;
		
		setSpacing(false);
		
		String width = "16em";
		String halfWidth = "8em";
		
		final Wound wound = new Wound();

		setSizeUndefined();
		
		//DateField - when is the wound recorded
		final DatePicker recorded = new DatePicker(MessageResources.getString("recordingDate") + ":");
		recorded.setValue(new Date());
		recorded.setLocale(getLocale());
		recorded.setInvalidAllowed(false);
		recorded.setWidth(width);
		recorded.setImmediate(true);
		
		addComponent(recorded);
		
		//ComboBox - body location code
		final NativeSelect location = new NativeSelect(MessageResources.getString("bodyLocationCode") + ":");
		for (BodyLocation b : BodyLocation.values()){
			location.addItem(b);
			location.setItemCaption(b, b.toFullString());
		}
		location.setValue(bodyLocation); //select chosen location
		location.setNullSelectionAllowed(false);
		location.setWidth(width);
		location.setEnabled(false);
		addComponent(location);
		
		//TextField - body location (in words)
		final TextField locationText = new TextField(MessageResources.getString("bodyLocation") + ":");
		locationText.setMaxLength(200);
		locationText.setWidth(width);
		locationText.setImmediate(true);
		
		addComponent(locationText);
		
		final NativeSelect level = new NativeSelect(MessageResources.getString("woundLevel") + ":");
		
		//ComboBox - wound type
		Collection<Object> typeIds = woundTypeProvider.getAll().getItemIds();
		final NativeSelect type = new NativeSelect(MessageResources.getString("woundType") + ":");
		for (Object o : typeIds){
			WoundType tmp = woundTypeProvider.getByID(o);
			type.addItem(tmp);
			type.setItemCaption(tmp, tmp.getClassification());
		}
		type.setWidth(width);
		type.setImmediate(true);
		type.addValueChangeListener(new ValueChangeListener(){

			@Override
			public void valueChange(ValueChangeEvent event) {
				WoundType woundType = (WoundType) type.getValue();
				level.removeAllItems();
				List<WoundLevel> levels = woundLevelProvider.getAllFoWoundType(woundType);
				for (WoundLevel wl : levels){
					level.addItem(wl);
					level.setItemCaption(wl, wl.getCharacterisation());
				}
			}
			
		});
		
		addComponent(type);
	
		level.setWidth(width);
		level.setImmediate(true);
		
		addComponent(level);
		
		//ComboBox - origination of wound
		final NativeSelect origination = new NativeSelect(MessageResources.getString("origination") + ":");
		for (Origination o : Origination.values()){