package com.github.averyregier.club.broker;

import com.github.averyregier.club.db.tables.records.OrganizationRecord;
import com.github.averyregier.club.domain.ClubManager;
import com.github.averyregier.club.domain.club.Program;
import com.github.averyregier.club.domain.club.adapter.ProgramAdapter;
import org.jooq.DSLContext;
import org.jooq.TableField;

import java.util.Map;
import java.util.Optional;

import static com.github.averyregier.club.db.tables.Organization.ORGANIZATION;
import static com.github.averyregier.club.domain.utility.UtilityMethods.convert;

/**
 * Created by avery on 2/27/15.
 */
public class OrganizationBroker extends Broker<Program> {
    public OrganizationBroker(Connector connector) {
        super(connector);
    }

    @Override
    protected void persist(Program program, DSLContext create) {
        if(create.insertInto(ORGANIZATION)
                .set(ORGANIZATION.ID, program.getId().getBytes())
                .set(mapFields(program))
                .onDuplicateKeyUpdate()
                .set(mapFields(program))
                .execute() != 1) {
            fail("Organization persistence failed: " + program.getId());
        }
    }

    private Map<TableField<OrganizationRecord, ?>, Object> mapFields(Program program) {
        return JooqUtil.<OrganizationRecord>map()
                .set(ORGANIZATION.CLUB_ID, program.getId().getBytes())
                .set(ORGANIZATION.ORGANIZATIONNAME, program.getShortCode())
                .set(ORGANIZATION.LOCALE, Optional.ofNullable(program.getLocale()).map(Object::toString).orElse(null))
                .build();
    }

    public Optional<Program> find(String id, ClubManager manager) {
        return query(create-> {
            OrganizationRecord record = create.selectFrom(ORGANIZATION)
                    .where(ORGANIZATION.ID.eq(id.getBytes()))
                    .fetchOne();
            if(record == null) return Optional.empty();
            return Optional.of(new ProgramAdapter(
                    record.getLocale(),
                    record.getOrganizationname(),
                    manager.lookup(convert(record.getClubId()))) {
                @Override
                public String getId() {
                    return id;
                }
            });
        });
    }
}

@@ -321,16 +321,40 @@
 ontext;%0A
+import org.jooq.Result;%0A
 import o
@@ -1753,16 +1753,23 @@
         
+Result%3C
 Organiza
@@ -1778,23 +1778,25 @@
 onRecord
+%3E
  record
+s
  = creat
@@ -1914,11 +1914,8 @@
 etch
-One
 ();%0A
@@ -1930,83 +1930,51 @@
     
-if(record == null) return Optional.empty();%0A            return Optional.of(
+return records.stream().findFirst().map(r-%3E
 new 
@@ -2006,29 +2006,24 @@
            r
-ecord
 .getLocale()
@@ -2045,21 +2045,16 @@
        r
-ecord
 .getOrga
@@ -2113,21 +2113,16 @@
 onvert(r
-ecord
 .getClub

fix ci