package datamysql

import (
	"database/sql"

	"bitbucket.org/nemt/nemt-portal-api/domain/entity"
	"bitbucket.org/nemt/nemt-portal-api/infra/errors"
)

// rideRepo maps methods to database
type zipcodeRepo struct {
	conn executor
}

func newZipcodeRepo(conn executor) *zipcodeRepo {
	return &zipcodeRepo{
		conn: conn,
	}
}

func (c *zipcodeRepo) getQuery() string {
	const (
		query = `SELECT 
										a.participating_zip_code_id,
										a.participating_zip_code_uuid,
										a.zipcode,
										(IFNULL(a.participating, b'0') = b'1') participating
							FROM
										tab_participating_zip_code a `
	)

	return query
}

// parseSet parses a result set result to an entity array
func (c *zipcodeRepo) parseSet(rows *sql.Rows, err error) ([]entity.Zipcode, error) {
	if err != nil {
		return nil, errors.Wrap(err)
	}
	result := make([]entity.Zipcode, 0)
	for rows.Next() {
		entity, err := c.parseEntity(rows)
		if err != nil {
			return nil, errors.Wrap(err)
		}
		result = append(result, entity)
	}
	return result, nil
}

// parseEntity parses a result to an entity
func (c *zipcodeRepo) parseEntity(row scanner) (retVal entity.Zipcode, err error) {
	err = row.Scan(
		&retVal.ID, &retVal.UUID, &retVal.Zipcode, &retVal.Participating)

	return retVal, errors.Wrap(err)
}

func (c *zipcodeRepo) GetAll() ([]entity.Zipcode, error) {
	return c.parseSet(c.conn.Query(c.getQuery()))
}

func (c *zipcodeRepo) GetByParticipatingZipcode(zipcode string) (entity.Zipcode, error) {
	return c.parseEntity(c.conn.QueryRow(c.getQuery()+"WHERE a.participating = 1 AND a.zipcode = ?", zipcode))
}
