import { all, call, put, takeLatest, select } from "@redux-saga/core/effects";
import {
  attemptEditProfile,
  attemptFetchProfile,
} from "../../request/profileRequest";
import {
  PROFILE_FETCH,
  PROFILE_MINE_FETCH,
  PROFILE_EDIT,
} from "../actions/profile/profileActionConstants";
import {
  editMineProfileError,
  editMineProfileSuccess,
  fetchErrorProfile,
  fetcHMineProfileError,
  fetchMineProfileSuccess,
  fetchProfileSuccess,
  //   editMineProfile,
  setMineProfile,
  setProfile,
} from "../actions/profile/profileActions";
import { selectUserId } from "../selectors/loginSelectors";

function* fetchProfile(payload) {
  try {
    const data = yield call(attemptFetchProfile, payload.payload);
    if (data) yield put(setProfile(data.data));
    yield put(fetchProfileSuccess());
  } catch (e) {
    yield put(fetchErrorProfile());
    console.log(e);
  }
}

function* fetchMineProfile() {
  try {
    const userId = yield select(selectUserId);
    const data = yield call(attemptFetchProfile, userId);
    if (data) yield put(setMineProfile(data.data));
    yield put(fetchMineProfileSuccess());
  } catch (e) {
    yield put(fetcHMineProfileError());
    console.log(e);
  }
}

function* changeMineProfile(payload) {
  try {
    let image;
    if (payload.payload.firmLogo.includes("data:image")) {
      image = payload.payload.firmLogo
        .replace("data:image/jpeg;base64,", "")
        .replace("data:image/jpg;base64,", "")
        .replace("data:image/png;base64,", "");
    } else if (payload.payload.firmLogo === "") {
      image = "";
    }

    const reqData = {
      company: {
        name: payload.payload.firmName,
        PIB: payload.payload.firmPIB,
        contacts: {
          telephone: payload.payload.firmPhone,
          location: payload.payload.firmLocation,
          web: payload.payload.firmWebsite,
        },
      },
      image: image,
    };

    if (payload.payload.firmLogo.includes("https")) delete reqData.image;

    const userId = yield select(selectUserId);
    const data = yield call(attemptEditProfile, userId, reqData);
    yield put(editMineProfileSuccess());
    if (payload.payload.handleApiResponseSuccess) {
      yield call(payload.payload.handleApiResponseSuccess);
    }
    console.log(data);
  } catch (e) {
    yield put(editMineProfileError());
    console.log(e);
  }
}

export default function* profileSaga() {
  yield all([
    takeLatest(PROFILE_FETCH, fetchProfile),
    takeLatest(PROFILE_MINE_FETCH, fetchMineProfile),
    takeLatest(PROFILE_EDIT, changeMineProfile),
  ]);
}
